.Net Core defines object.ToString() as public virtual string? ToString();
This means that code such as the following provokes a CS8602 "Dereference of a possibly null reference" warning:
object t = "test";
var s = t.ToString();
Console.WriteLine(s.Length); // Warning CS8602
This is easily fixed by writing s!.Length or t.ToString()!;, but my question is:
Under what circumstances would it ever be correct to return null from an implementation of object.ToString()?
The answer would appear to be: "You should never return null from object.ToString()", which is fair enough - but that does raise another question, which is "in that case, why did Microsoft declare it as public virtual string? ToString();" ?
Aside:
Some comments below suggest that because an implementation could incorrectly return null, then the return value must be declared as string?.
If that was true, then why doesn't the same logic apply to ICloneable.Clone(), which is not declared as returning object? ?
And surely this logic would apply to every single interface method that returned a reference type? Any implementation of such a method (for example, ICustomFormatter.Format()) in theory could return null - and thus the return value should be nullable. But they are not.
Having read the link provided by DavidG, I believe the discussion in that topic answers the question to my satisfaction: