Home > Enterprise >  c# record without curly brackets
c# record without curly brackets

Time:10-10

I noticed by chance that the following code compiles (VS2022preview , c#10):

record R {
  public R() {}
  int I;
}

record B : R; // no curly brackets !

(see: https://sharplab.io/#v2:EYLgxg9gTgpgtADwGwBYA tJQCYAIBKuA3gLABQuluAAgMwEAUAlMQL7lW4CWAdgC64AkgG5y7MuUzQ8AIVwgCwoA===)

I am curious how does this work without curly brackets for B ? is this in the standard ?

(this does not work if I change the record to class)

CodePudding user response:

In the C# language specification for records https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-9.0/records, the record_body clause is specified as

record_body
    : '{' class_member_declaration* '}' ';'?
    | ';'
    ;

Therefore, the curly braces may be omitted.

CodePudding user response:

https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/tutorials/records

Pretty much what documentation says. C# 9.0 introduced many such changes. Top level program file, top level namespace declaration etc where they got rid of mandatory curly braces.

  • Related