top of page

C# tips and tricks - part 2

Switch property pattern

Switch property pattern allows you to check the values of one or more properties of an object directly in the switch expression without having to create complex if checks. Here's an example using the Student class from the example above:



string description = student switch
{
    { FirstName: "John", Age: 25 } => "John is 25 years old",
    { FirstName: "John", Age: 30 } => "Jane is 30 years old",
    { Age: > 18 } => "Adult",
    { Age: < 18 } => "Minor",
    _ => "Unknown student"
};

Console.WriteLine(description);  // Jane is 30 years old

  • { Name: "John", Age: 25 }: This pattern checks if the Name property of the object is "John" and Age is 25. If so, it will return the text "John is 25 years old".

  • { Age: > 18 }: Checks if Age is greater than 18, regardless of the name.

  • _ => "Unknown student": This is the "catch-all" expression that covers all other cases that were not caught by the previous rules.






Amexis Team

9 views0 comments

Recent Posts

See All

Коментарі


bottom of page