Home > Net >  c# record short syntax private members
c# record short syntax private members

Time:12-04

This is not legal (why?):

record Rec(int Field1, string Field2, private int PrivateField) { .. }; 

Just to have the private field I now need to switch to the tedious long form:

record Rec 
{
  public int Field1 { get; init; }
  public string Field2  { get; init; }
  int PrivateField  { get; init; } 

  public Bla(int field1, string field2, int privateField) 
  {
    Field1=field1;
    Field2 = field2;
    PrivateField = privateField;
  }

  ...
}

Is there a better way ?

CodePudding user response:

I suggest:

record Rec(int Field1, string Field2)
{
    int PrivateField;
};

CodePudding user response:

you can create an abstract base record with a protected field. It will behavior the same way as a private one

public record Rec(int Field1, string Field2, int PrivateField) : Base(PrivateField)

public abstract record Base
{
    protected int  PrivateField; //or { get; init; }

    public Base(int privateField)
    {
        PrivateField=privateField;
    }
}
  • Related