Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# 9.0 records - ToString not inherited

consider:

// the ratioale for Wrapper is that it has a Json serializer that  
// serialize through Field (not included in this example)
record Wrapper<T> where T : notnull {
  protected Wrapper(T field) => Field = field; 
  protected Wrapper(Wrapper<T> wrapper) => Field = wrapper.Field;
  protected readonly T Field;
  public override string ToString() => Field.ToString() ?? "";
}

record MyRec : Wrapper<string> {
    public MyRec(string s) : base(s) {}
}

public static class Program {
  public static void Main(string[] args) {
      var r = new MyRec("hello");
      Console.WriteLine(r.ToString());
  }
}

sharplab

seems like base ToString is not inherinted and the compiler still autogenerates derived Tostring

Why is that ? is there any good way around it ?

like image 283
kofifus Avatar asked Dec 17 '22 12:12

kofifus


1 Answers

There is a comment which has fixed this issue for me. Sean says if you add sealed to the method it stops the compiler from synthesizing the ToString method see below:

public sealed override string ToString() => Value;

Note that the ability to seal an override of ToString was introduced in C# 10.

like image 59
Billy Avatar answered Dec 24 '22 01:12

Billy