C# 7 and .NET Core 2.0 High Performance
上QQ阅读APP看书,第一时间看更新

Type pattern

The type pattern can be used with an object to verify whether it matches the type or suffices the expression based on the conditions specified. Suppose we need to check whether the PersonID is int; assign that ID to another variable, i, and use it in the program, otherwise return:

if (!(person.ID is int i)) return; 
 
Console.WriteLine($"Person ID is {i}"); 

We can also use multiple logical operators to evaluate more conditions, as follows:

if (!(person.ID is int i) && !(person.DOB>DateTime.Now.AddYears(-20))) return;   

The preceding statement checks whether the Person.ID is null or not and whether the person is older than 20.