top of page

C# tips and tricks - part 2

  • 3634795
  • Sep 26, 2024
  • 1 min read

Updated: Oct 16, 2024

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.



ree



Amexis Team

Comments


Amexis Logo

Sofia, 6 Al. Zhendov str
Plovdiv, 26a Petko Karavelov str

info@amexis.net
+359 88 212 3791

Have you worked with us before?

Follow Us On:

  • LinkedIn
  • Facebook

© 

© 2024 by Amexis
All rights reserved.

© 2024 by Amexis
All rights reserved.

© 2024 by Amexis
All rights reserved.

bottom of page