We are aware of is-Expression where we can use is keyword to verify the given type. In C# 7.0, this has been extended to constant, type, and var patterns as well. Let's dig into each of the patterns here.
Pattern Matching with constants
Earlier in is-Expressions, we used to match the variable types but now, we can even verify and validate for constants too. See the code below.
- public void PatternMatchingWithConstants() {
- int age = 50;
- if (age is 50) {
- //Do write some logic here
- }
- }
As observed in the above code, we are validating a constant value using is-Expression in an "if" block.
Pattern Matching with Types
As we see in the above code, we validated the constants. Similarly, we can validate the type of a given variable in the "if" block as shown below.
- public void PatternMatchingWithType() {
- object age = 50;
- if (age is int) {
- int myage = (int) age;
- //Do write some logic here
- }
- }
In addition to this, we are given other flexibility here. As observed in the above code, we perform two actions. First, we are verifying if the age type is int or not; and once it is true, then we are type casting it to another variable. Now, we can do these two actions in a single step, i.e., validating and assigning to a variable the if condition success.
- object age = 50;
- if (age is int myage) {
- //Do write some logic here
- }
In the above code, the age will be verified as type int or not. Then, it will be type-casted and assigned to myage in a single step.
Type pattern matching can also be applied at inheritance. It will verify whether the given class object is inherited by a base class or not, as shown below.

XxxsenatorxxxPosted Jan 15, 2019, 11:00 PM
@Sai Kumar Koona Please see this: https://www.c-sharpcorner.com/forums/how-to-use-servicebll-in-formwindowsform-with-di
Rehman ShahidPosted Oct 6, 2018, 11:42 PM
Nice one.......
Sanghamitra MohantyPosted Oct 6, 2018, 6:55 AM
This is really nice one