Please, note that this question is about the latest C# 8 nullable-references, I've enabled it in csproj file by the following <Nullable>enable</Nullable> declaration.
Consider the following simple code
class SortedList<T> where T : struct, IComparable, IComparable<T>, IConvertible, IEquatable<T>, IFormattable
{
private Node? _node;
private readonly IComparer<T> _comparer = Comparer<T>.Default;
class Node
{
public Node(T value)
{
Value = value;
}
public T Value { get; }
public Node? Next { get; set; }
public override string ToString()
{
return Value.ToString();
}
}
//rest of code, that isn't important
}
The line return Value.ToString(); gives me a CS8603 Possible null reference return warning and my question actually why is it here?
I'm using the where T : struct, IComparable, IComparable<T>, IConvertible, IEquatable<T>, IFormattable generic constraint to match a numeric types, Value is value type actually, not the reference one. There is also no overload of ToString() to any value type, the default implementation for Int32 (for example) returns non-nullable string. MSDN notes to inheritors is also saying that
Your
ToString()override should not returnEmptyor anullstring.
Does the compiler complaining about some type, which can satisfy the generic constraint and return null from ToString()?
I can avoid the warning by making a return type nullable
public override string? ToString()
{
return Value.ToString();
}
or by using the null-coalescing operator
public override string ToString()
{
return Value.ToString() ?? "";
}
or by null-forgiving operator
public override string ToString()
{
return Value.ToString()!;
}
But these options look like a tricks mostly, I'm looking for explanation of this behavior, why is there, by design or any other reasons were take place? Is there any ways to avoid the warning, except those above?
Btw, this option doesn't work, warning still in place
[return: MaybeNull]
public override string ToString()
{
return Value.ToString();
}
I'm using .NET Core 3.1 and VS 2019 16.4.2, but I don't think it's really important here. Thanks in advance for help!
ToStringshouldn't return a null string, return something meaningful. - zagglerobject.ToString()should returnstring?orstring(although I can't find it now). The conclusion was that although the guidance was to never return null, in fact a lot of code existed which could return null (including code which returned the result of callingToString()on one of its members). Therefore makingobject.ToString()returnstringwould introduce a lot of warnings into most people's code. To keep the noise down, they decided to document what actually happens in practice, but allow you to returnstringif you wanted. - canton7