Skip to main content

Extended property patterns in c#

In C#, extended property patterns allow you to use the is operator to check if an object has a particular property and access the value of that property. This can be useful when working with objects that have many properties and you only need to access a specific property.

Here's an example of how to use extended property patterns in C#:

public class Person { public string FirstName { get; set; } 
public string LastName { get; set; } } 
Person person = new Person { FirstName = "John", LastName = "Doe" }; 
if (person is { FirstName: string firstName }) 
{ 
Console.WriteLine($"First name: {firstName}"); 
}

In this example, the if statement uses an extended property pattern to check if the person object has a FirstName property of type string. If the person object has a FirstName property, the value of the property is assigned to the firstName variable, which is then used to print the first name to the console.

You can also use extended property patterns in switch statements and with other C# language features such as foreach loops and LINQ queries.


switch (person) { 
case 
{ FirstName: string firstName }: 
Console.WriteLine($"First name: {firstName}");
 break; case { LastName: string lastName }:
 Console.WriteLine($"Last name: {lastName}"); break; }
 

Extended property patterns can make your code more concise and easier to read, especially when working with objects that have many properties. However, they can also make your code more difficult to understand if they are not used correctly, so it is important to use them appropriately.

Comments