Skip to content

Proposal: Pattern matching and record types #206

Closed

Description

@gafter

The spec has been moved

The specs for pattern matching and records have been moved to https://github.com/dotnet/roslyn/blob/features/patterns/docs/features/patterns.md and https://github.com/dotnet/roslyn/blob/features/records/docs/features/records.md

There are new discussion threads at #10153 for pattern-matching and #10154 for records.

Activity

  1. self-assigned this
    on Feb 3, 2015
  2. ghord commented on Feb 3, 2015

    @ghord

    Overall, great proposal.
    Just a minor nitpcik: * seems a little out of place in language. I propose to simply use var instead by omitting variable name:

    case Mult(var, Const(0)): return Const(0);
    case Mult(Const(1), var x): return Simplify(x);
    

    If we would allow to match by only type name and skip variable name, one could even perform simple type test cases like this:

    bool IsInteger(Expr e) 
    {
        switch(e) 
        {
    
            case Const(int): return true;
            case Const(double val): return IsInteger(val);
            case Const(var): return false;
            ...
        }
    }
    

    I think it would be more consistent behaviour.

  3. ztone commented on Feb 3, 2015

    @ztone

    F# record (for reference)

    type Cartesian = { X : double; Y : double }
    let c = { X = 1.0; Y = 2.0 }

    This is similar valid C# syntax

    class Cartesian { public double X; public double Y; }
    var c = new Cartesian { X = 1.0, Y = 2.0 };

    Proposal. This is a example of a simple syntax transition to a c# record from the code above. The record is an immutable class with just default public readonly fields. Records could use the expected immutable class implementation.

    record Cartesian { double X; double Y; }
    var c = new Cartesian { X = 1.0, Y = 2.0 };
    
    var ok = c.X; // ok
    c.X = 3.0; // Error, a readonly field cannot be assigned to.

    Another option could be (although I would prefer the above)

    record Cartesian { double X; double Y; }
    var c = new Cartesian(X: 1.0, Y: 2.0);
    
    var ok = c.X; // ok
    c.X = 3.0; // Error, a readonly field cannot be assigned to.

    Just my 2 cents

  4. casperOne commented on Feb 3, 2015

    @casperOne

    Why would IEquatable<T> not be implemented? You're overriding Equals(object) already, so IEquatable<T> should be a no-brainer.

  5. SolalPirelli commented on Feb 3, 2015

    @SolalPirelli

    I may be reading the spec wrong, but it doesn't look like it's specifying the return type of operator is. Shouldn't it force it to be bool? The == and != operators lack such a constraint, but IMHO there is no valid use for non-bool-returning equality operators.

  6. mpawelski commented on Feb 3, 2015

    @mpawelski

    Were you considering to use _ character instead of * for wildcard pattern? Every language I can think of use this character for that.
    I sometimes use this character as lambda argument to indicate that this parameter won't be used. I know that _ is a valid name for variables and classes and you can write something like this (_, other) => _.PropertyAccess but maybe there is a way to use this character and don't break existing code? For example previous code would compile (maybe with warning) and this one would fail (_, _) => _.PropertyAccess because _ would be treated as a wilcard character.

    And when it comes to pattern matching we could disallow to name variable as _ (for examle this pattern Cartesian(var x, var _) won't compile) and allow _ to be wilcard character. It's a new feature so old code won't be broken.

    I just thing that _ is so prevalent in other languages that it is worth considering to use it instead of *. For someone familiar with pattern matching from other language it would be instantaneously clear what the code do when they'll see C# code with pattern matching and with this character. I think similarity with other languages is nice to have.

  7. MgSam commented on Feb 4, 2015

    @MgSam

    Great to see the updated proposal!

    Some comments:

    • The example shows auto-implementing of ToString, but the spec says only that Equals and GetHashCode will be implemented.
    • I think auto-implementing of the == and != operators is a no-brainer here. IEquatable I don't feel strongly about as I never see types that actually use it.
    • I like the record keyword. It seems weird that the mere existence of a primary constructor would initiate all this other magic behavior as well. Doing so may lead non-primary constructor classes to become second class citizens (as auto-implementation of GetHashCode, Equals, and ToString will do the right thing in 95% of cases and thus be highly desirable). IMO, the magic associated with records seems orthogonal to primary constructors.
    • I really hope the design committee looks at the with operator. Immutability/records needs this operator to be useful without a ton of extra boilerplate for copying immutable types. As others have mentioned previously, Roslyn code would also benefit greatly from a with operator.
    • The biggest value adds for the code I write every day are records (mostly as proposed) + with operator. The pattern matching stuff is just nice to have gravy.
  8. gafter commented on Feb 4, 2015

    @gafter
    MemberAuthor

    These record types can easily support 'with' expressions like

    Point p = ...;
    p = p with { X: 4 };

    which would generate

    p = new Point(4, p.Y);
  9. gafter commented on Feb 4, 2015

    @gafter
    MemberAuthor

    The == and != operators would only be a good idea for record structs. It is too easy to get in trouble with them on reference types.

  10. MrJul commented on Feb 4, 2015

    @MrJul
    Contributor

    @MgSam IEquatable<T> is often used implicitly, for example in a Dictionary<TKey,TValue> or a HashSet<T> with the default comparer. EqualityComparer<T>.Default uses IEquatable<T> if it's available, or falls back to Object.Equals if it doesn't, meaning a perf/memory hit for value types due to boxing.

  11. 251 remaining items

  12. HaloFour commented on Mar 25, 2016

    @HaloFour

    @gordanr

    So spit-balling with #119:

    public class Student(string Name, double Gpa)
        requires Name != null else throw new ArgumentNullException(nameof(Name))
        requires Gpa > 0.0 else throw new ArgumentException(nameof(Gpa)); 

    Or with #8181:

    public class Student(string Name, double Gpa) {
        guard (Name != null) else throw new ArgumentNullException(nameof(Name));
        guard (Gpa > 0.0) else throw new ArgumentException(nameof(Gpa));
    }

    In either case the contract could be applied to both the constructor and the generated With method.

  13. gordanr commented on Mar 25, 2016

    @gordanr

    Or even simpler with help of non-nullable reference types.

    public class Student(string Name, double Gpa)
        requires Gpa > 0.0 else throw new ArgumentException(nameof(Gpa));
    }
    

    That would be really awesome. Meanwhile we can only use explicit constructor.

  14. HaloFour commented on Mar 25, 2016

    @HaloFour

    @gordanr Nod, the enforcement maybe as a last resort, just in case someone squeaks a null through anyway.

  15. orthoxerox commented on Mar 25, 2016

    @orthoxerox
    Contributor

    Looks like the spec is missing the changes to the class-base part of the declaration:

    If there are arguments in the class-base specification, a base constructor selected by overload resolution with these arguments is invoked;

    In the current c# spec, class-base is:

    class-base:
        :   class-type
        :   interface-type-list
        :   class-type   ,   interface-type-list
    
  16. orthoxerox commented on Mar 25, 2016

    @orthoxerox
    Contributor

    @gafter

    We have not specified ToString for records, nor operator == and operator !=. It is an open question whether or not we will do anything for them.

    I'm not sure if a default ToString will be useful beyond debugging output. Maybe a default DebuggerDisplayAttribute will be more useful?

    I like the idea of public Student { ... } to add code to the primary constructor.

    +1 to that idea

    We have solved the Square:Rectangle problem. The solution appearing in the draft specification is not the one we are going to end up with, but this margin is too small to hold the details. Stay tuned for more details.

    I'm excited. Current spec forces you to use only abstract rectangles, if I'm reading it correctly.

  17. DavidArno commented on Mar 25, 2016

    @DavidArno

    Regarding the open questions/undecided stuff:

    Please implement == & != for records. I can't really see a case where one would not want == implemented exactly the same as .Equals() as shown in the examples. Not implementing them will therefore force everyone to either manually define them for every record (sort of defeating one of the point of records, to cut down on boiler-plate, or to force exclusive use of.Equals when handling records.

    The with expression is a useful syntactic-sugar addition. Considering @HaloFour's example, what will really happen without this is peoples will write var bar = foo.With(123);, dropping the optional X:. Much better to provide a language feature that guides the developer into writing clearer code: var bar = foo with { X = 123 };. This offers a massive improvement in readability for very little compiler cost.

  18. DavidArno commented on Mar 25, 2016

    @DavidArno

    In the examples, both a sealed and abstract class record are shown. But the spec shows class-modifiers as optional, suggesting class records can be declared that are neither. What would be the point of them and what would the resultant syntax look like?

  19. Joe4evr commented on Mar 26, 2016

    @Joe4evr

    what will really happen without this is peoples will write var bar = foo.With(123);

    This can be mitigated by shipping an analyzer+codefix in the box. In a case like this, I'd rather MS provide one rather than every Roslyn analyzer author implementing their own.

  20. alrz commented on Mar 26, 2016

    @alrz
    Member

    @gafter I do like to see with syntactic sugar for the sake of CamelCase property names. For the same reason I don't think a dedicated syntax to name the parameters and properties differently would be deadly useful unless you want to follow the naming convention when you write named arguments in the constructor. That said, I think the ability to use object initializer syntax for record construction can provide this code style consistency, specially when you have default values for properties and want to omit some of them short of their order using named arguments (Note that with with this is always the case).

    As for @HaloFour's suggestion, to not look like a property, how about something similar to C++ syntax?

    public sealed class Student(string Name, double Gpa) {
      // no parameters permitted
      default private Student() {
        // additional logic, if any
      }
      // still you can define a ctor without parameter
      private Student() : this("Batman", -1) {}
      public static Student Create() { ... }
    }

    Although the primary constructor should be accessible publicly for deconstruction short of its accessibility.

  21. gafter commented on Mar 28, 2016

    @gafter
    MemberAuthor

    The specs for pattern matching and records have been moved to https://github.com/dotnet/roslyn/blob/features/patterns/docs/features/patterns.md and https://github.com/dotnet/roslyn/blob/features/records/docs/features/records.md

    There are new discussion threads at #10153 for pattern-matching and #10154 for records.

  22. added
    Resolution-Not Applicable
    and removed
    4 - In Review
    on Mar 28, 2016
  23. added a commit that references this issue on Sep 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions