December 12, 2024

Using Patterns in if and switch statements

Using Patterns in if and switch statements See this link: https://www.thomasclaudiushuber.com/2021/02/18/c-9-0-improved-pattern-matching/ Replace the old inefficient
ChangedEvent lce = ev as ChangedEvent
if (lce != null)
{
  DoSomethingWith(lce);
}
to this much shorter and more readable:
if (ev is ChangedEvent lce)
{
  DoSomethingWith(lce);
}
And this has been refined further with much more readable conditional clauses using patterns
var developer = new Developer { YearOfBirth = 1983 };
if (developer is { YearOfBirth: >= 1980 and <= 1989 and not 1984 })
{
  // The dev is born in the eighties, but not in 1984
}
And when checking for is or is not null use this pattern
if (developer is not null)
{
  ...
}
We can also use these patterns in switch statements TODO add an example Now we have "and" and "&&" plus "or" and "||": The "and" pattern combinator is used to combine patterns. The conditional "and" operator of "&&" is a boolean operator and it is used to combine bool values in your C# code. Similar statements can be made for the pattern "or" and "not" clauses