Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use indexers in switch expression?

How to access indexers in switch expression? There is a nice property pattern syntax in switch expressions, but I can't figure out or find any information about using indexers.

Given following code:

var a = "123";
if(a.Length == 3 && a[0] == '1')
    Console.WriteLine("passed");

How do to convert it to switch expression? Matching a.Length is easy, but how to specify a match for a[0] == '1'?

var b = a switch
{
    { Length: 3, this[0]: '1' } => "passed", // CS8918: Identifier or a simple member access expected.
    _ => "error"
};
Console.WriteLine(b);

Fiddle.

like image 282
Sinatr Avatar asked Feb 04 '26 04:02

Sinatr


1 Answers

One way to do it is by using when statement. It is not as beautiful as property pattern, but can be a workaround:

var b = a switch
{
    { Length: 3 } when a[0] == '1' => "passed",
    _ => "error"
};
like image 146
Dmitrii Dovgopolyi Avatar answered Feb 05 '26 16:02

Dmitrii Dovgopolyi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!