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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With