
Patterns
The other big addition is you can now match patterns in C# 7 using the is keyword. This simplifies testing for null and matching against types, among other things. It also lets you easily use the cast value. This is a simpler alternative to using full polymorphism (where a derived class can be treated as a base class and override methods). However, if you control the code base and are able to make use of polymorphism properly, then you should still do this and follow good object-oriented programming (OOP) principles.
In the following example, pattern matching is used to parse the type and value of an unknown object:
private static int PatternMatch(object obj)
{
if (obj is null)
{
return 0;
}
if (obj is int i)
{
return i++;
}
if (obj is DateTime d ||
(obj is string str && DateTime.TryParse(str, out d)))
{
return d.DayOfYear;
}
return -1;
}
You can also use pattern matching in the case of a switch statement, and you can switch on non-primitive types, such as custom objects.