I encountered this while enabling the nullable feature in our projects.
In Net 5.0 the signature for object.ToString()
is
public virtual string? ToString ();
Why is that? The notes to Inheritors even state
Your ToString() override should not return Empty or a null string.
so why does the signature state that it can? I could not find any info on that.
But my ideas are
- Backwards comparability for those people who didn't read the note mentioned above and return null from their ToString method.
- To let the people who read the mentioned note ignore it
But since we want to treat the warnings that come with the nullable feature as errors now we have to add !
or a null check everywhere we use ToString
.
Is there any other good reason why the signature is as it is?
CodePudding user response:
Backwards comparability for those people who didn't read the note mentioned above and return null from their ToString method.
It's exactly this: there are real-world ToString implementations out there that return null
. See this discussion for full details.
You'll notice that if you write your own ToString method in VS, the return type defaults to string
not string?
however -- this is to encourage you to follow the guidelines. If you use a type which defines its own ToString
method and uses NRTs, it will probably also return string
, and you won't need to nullcheck it.
The fact that object.ToString()
returns string?
is only relevant:
- When you've cast an object to
object
, and the compiler doesn't know whether its overriddenToString
method actually returnsstring?
orstring
- When you're using an unconstrained generic type, for the same reason
C c = new C();
string s1 = c.ToString(); // No warning
object o = c;
string s2 = o.ToString(); // Warning
public class C
{
public override string ToString() => "";
}