Search code examples
c#c#-9.0record-classes

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 ?


Solution

  • 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.