This is a continuation of my previous post, where I am trying to complete reading this book:
So, C# 7.0 also introduce pattern matching in switch statement. Consider below example function:
public static string detectParam(object o) { switch (o) { case int i when i > 10: return "Big Integer"; case int i: return "Integer"; case double d when d > 10: return "Big Double"; case double d: return "Double"; case string s: return "String"; default: return "Object"; case null: return "Null"; } }
We can then test the output of the function:
public static void Main() { object o = 15; Console.WriteLine($"{o} is {detectParam(o)}"); // 15 is Big Integer object o1 = 9; Console.WriteLine($"{o1} is {detectParam(o1)}"); // 9 is Integer object o2 = 15.1; Console.WriteLine($"{o2} is {detectParam(o2)}"); // 15.1 is Big Double object o3 = 9.9; Console.WriteLine($"{o3} is {detectParam(o3)}"); // 9.9 is Double object o4 = "15"; Console.WriteLine($"{o4} is {detectParam(o4)}"); // 15 is String object o5 = new Object(); Console.WriteLine($"{o5} is {detectParam(o5)}"); // System.Object is Object object o6 = null; Console.WriteLine($"{o6} is {detectParam(o6)}"); // is Null }
We can actually shorten the switch statement even further:
public static string detectParam(object o) { var result = o switch { int i when i > 10 => "Big Integer", int i => "Integer", double d when d > 10 => "Big Double", double d => "Double", string s => "String", null => "Null", _ => "Object" }; return result; }
GD Star Rating
loading...
C# 7.0 Pattern Matching In Conditional Logic - Part 2, loading...
About Hardono
Howdy! I'm Hardono. I am working as a Software Developer. I am working mostly in Windows, dealing with .NET, conversing in C#. But I know a bit of Linux, mainly because I need to keep this blog operational. I've been working in Logistics/Transport industry for more than 11 years.
Incoming Search
.net, c#