Roslyn: Property patterns with generics give a syntax error

Created on 22 Jul 2019  路  5Comments  路  Source: dotnet/roslyn

I'm trying to replicate some light Option\ on C#8, but I'm getting an error in the switch expression

Consider the code:

   public abstract class Option<T> { }
   public class None<T> : Option<T> { }
   public class Some<T> : Option<T> {
       public T Value { get; }
       public Some(T value) => Value = value;
   }

If i try property pattern on Some\ the compiler throws a syntax error

static string Match(Option<Foo> maybeFoo) =>
    maybeFoo switch
    {
        // works
        None<Foo> _ => "Theres nothing",

        // works
        Some<Foo> someFoo when someFoo.Value.Bar > 42 => someFoo.Value.Baz,

        // Syntax error
        Some<Foo> { Value: var p } when p.Bar == 42 => p.Baz,

        _ => string.Empty,
    };

If I define a Type alias to Some\ it works as expected

using SomeFoo = Program.Some<Foo>;

static string Match(Option<Foo> maybeFoo) =>
    maybeFoo switch
    {
        // works
        None<Foo> _ => "Theres nothing",

        // now works
        SomeFoo { Value: var p } when p.Bar == 42 => p.Baz,

        _ => string.Empty,
    };
Area-Compilers Bug

All 5 comments

Have you tried adding a deconstructor?

@orthoxerox yeah, works with deconstructor.

Like this
https://github.com/dotnet/csharplang/issues/883#issuecomment-513598593

This code fails to compile, because the rules used by the compiler to decide between interpreting <> as generic type markers and comparison operators didn't take property patterns into account.

I have submitted https://github.com/dotnet/roslyn/pull/37898 in an attempt to fix that.

@svick I am just back from vacation. I will look at this tomorrow.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

joshua-mng picture joshua-mng  路  3Comments

DavidArno picture DavidArno  路  3Comments

marler8997 picture marler8997  路  3Comments

asvishnyakov picture asvishnyakov  路  3Comments

MadsTorgersen picture MadsTorgersen  路  3Comments