Search code examples
c#switch-expressionproperty-pattern

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.


Solution

  • 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"
    };