7

Introducing C# 10: Extended property patterns

 3 years ago
source link: https://anthonygiretti.com/2021/07/27/introducing-c-10extended-property-patterns/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Introducing C# 10: Extended property patterns

2021-07-27 by anthonygiretti

Introduction

C# 8 has introduced a new pattern: Property pattern. This pattern enables you to match on properties of the object examined, if you missed that feature, here is the Microsoft documentation here: Property pattern. C# 10 improves that pattern by simplifying access to nested properties. In the article I’ll show what it is.

Example

The following code sample shows a C# 8 tax calculator, which involves an object named CalculateTax and its nested property named ProvinceOrStateTaxProperty which is itself an object:

namespace DemoCsharp9 { public class ProvinceOrStateTaxProperty { public string ProvinceOrState { get; set; } }

public class CalculateTax { public string CountryName { get; set; } public ProvinceOrStateTaxProperty ProvinceTaxProperty { get; set; } }

public class Computing { private static decimal ComputePrice(CalculateTax calculate, decimal price) =>

calculate switch {

{ ProvinceTaxProperty: { ProvinceOrState: "Québec" } } => 1.14975M * price,

{ ProvinceTaxProperty: { ProvinceOrState: "Alberta" } } => 1.05M * price,

{ ProvinceTaxProperty: { ProvinceOrState: "Ontario" } } => 1.13M * price,

_ => 0

}; } }

The syntax to access the nested property is a bit verbose:

{ ProvinceTaxProperty: { ProvinceOrState: "Value" } }

C# 10 fixes that and allows to access directly the nested property by a dot:

namespace DemoCsharp10 { public class ProvinceOrStateTax { public string ProvinceOrState { get; set; } }

public class CountryTax { public string CountryName { get; set; } public ProvinceOrStateTax ProvinceTaxProperty { get; set; } }

public class Computing { private static decimal ComputePrice(CountryTax calculate, decimal price) =>

calculate switch {

{ ProvinceTaxProperty.ProvinceOrState: "Québec" } => 1.14975M * price,

{ ProvinceTaxProperty.ProvinceOrState: "Alberta" } => 1.05M * price,

{ ProvinceTaxProperty.ProvinceOrState: "Ontario" } => 1.13M * price,

_ => 0

}; } }

Much more practical isn’t it ? 😉

Like this:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK