Skip to main content

Posts

Showing posts with the label C# 11.0 features

C# 11.0 : List Patterns

Introduction In C# 11, a game-changing feature was introduced – List Patterns. These patterns enable you to effortlessly match an array or a list with a sequence of elements. Let's explore the three distinct list pattern matching techniques Discard Pattern The Discard Pattern is useful when you know the length of the sequence. For instance, matching an array of five integers against another array with the same values var ids = new [ ] { 1 , 2 , 3 , 4 , 5 } ; if ( ids is [ 1 , 2 , 3 , 4 , 5 ] ) { Console . WriteLine ( "Its matched" ) ; } C# Copy To match regardless of the values, you can use the underscore (_) if ( ids is [ _ , _ , _ , _ , _ ] ) { Console . WriteLine ( "Its matched" ) ; } C# Copy Range Pattern When you're unsure about the sequence length, the Range Pattern comes into play. Use two dots (..) to specify any number of elements. For instance if ( ids is [ 1 , .. ] ) { Console . WriteLine ( "...