Features in C# 7 - Pattern matching
Hello Readers, In This blog post I have explained about two new features introduced
with C# 7.0. (Along with other features like Tuples,local functions,ref return and
ref local,throw expression, Deconstruction,Literal improvements,Generalized Async
return types,More expression bodied members).
- Pattern Matching
- Out variable ( with enhancement)
Pattern Matching
Patterns are already
exists in the programming world.But C# has introduced for the first time in it's
latest version 7.0( as of VS 2017).
C# 7.0 version allows
us to use a pattern in existing "is" statement and with "switch" statement and allows
us to compare whether value has certain type or not. We can match pattern with any
data type including custom type.Pattern matching allows us to confirm what the object
is of type and then hold it into a variable if it was the type we were expecting,
is met.
Patterns can be
Constant Pattern which test the input value with constant expression.
Constant Pattern which test the input value with constant expression.
if (o is null) return; // constant pattern "null"
var pattern where input value will be assigned to primitive
type based on the value.
if (o is var x) Console.WriteLine($"it's a var
pattern with the type {x?.GetType()?.Name}");
type pattern where it checks whether input has a certain type.
if (!(o is string s)) return; // type pattern "string s"
Console.WriteLine(new string('*', s));
Note: Here we
need to understand that "is" is not same as "==" operator
example
string salFromConsole= "20000";
decimal salFromDatabase = 500000.00;
object salVal = ageFromDatabase;
if (salVal is decimal salary) || (salVal is string salText && decimal.TryParse(salText, out salary)))
{
Console.WriteLine($"Your salary is { salary}.");
}
else
{
Console.WriteLine("salary is not known.");
}
Pattern with Switch
Statement
In C# 7.0 Patterns
are added to switch statement to enhance the usage of switch.
- we can switch on to any type (not just primitive types, as with previous versions)
- Patterns can also be used in case clauses
- Case clauses can have additional checking on them
switch(shape){
case Circle c:
WriteLine($"circle with radius {c.Radius}");
break;
case Rectangle s when (s.Length == s.Height):
WriteLine($"{s.Length} x {s.Height} square");
break;
case Rectangle r:
WriteLine($"{r.Length} x {r.Height} rectangle");
break;
default:
WriteLine("");
break;
case null:
throw new ArgumentNullException(nameof(shape));
}
Out variables
Before C# 7.0 version,
we used out variables where the variable is declared first before
using it.
But in C# 7.0 we can declare the out variable at the place where it is passed to
the method as shown in the below example.
public void getName(out string fullname)
{
fullname = "syed khaleel";
}
getName(out string fullname); // declared inline
Console.WriteLine($"{fullname}"); // variable fullname is accessible here
Here we need to remember that, the variables are in scope of the
nearest closing block.
A common use of out
variables is the
Try...
pattern.
where the return
value indicates success/failure , and out parameters holds the results obtained:
if (int.TryParse(s, out var x))
{
WriteLine($"{x}");
}
few points to note while using pattern with switch.
Evolution of C# in a picture...
- The null clause at the end is not unreachable
- The order of case clauses now matters
- The default clause is always evaluated last
Evolution of C# in a picture...
Hope you understand
this post.If you enjoy reading this blog post.Please comment below and like my facebook
page for more updates...
Thanks.
Dotnetcodetree
Dotnetcodetree
Comments
Post a Comment