-
Notifications
You must be signed in to change notification settings - Fork 5.2k
Closed as not planned
Closed as not planned
Copy link
Labels
Description
Description
In the Nullable struct, we can find the following ToString()
implementation:
public override string? ToString() => hasValue ? value.ToString() : "";
The return type is a nullable string, so when calling ToString()
on a null value, I'm expecting to get null
rather than an empty string.
It's a misleading behavior.
Reproduction Steps
using System.Diagnostics;
namespace MyApp;
class Program
{
static void Main(string[] args)
{
int? nullValue = null;
Debug.Assert(string.Empty == nullValue.ToString());
}
}
Expected behavior
I would expect either:
- Get a null value:
ToString()
returns null when there is no value:
public override string? ToString() => hasValue ? value.ToString() : null;
- A compilation warning so you can avoid unexpected behavior.
Actual behavior
ToString()
is returning ""
when called on a null value.
Regression?
No response
Known Workarounds
Use the null-conditional operator (but you can easily forget to do so):
using System.Diagnostics;
namespace MyApp;
class Program
{
static void Main(string[] args)
{
int? nullValue = null;
Debug.Assert(null == nullValue?.ToString());
}
}
Configuration
Tested with .NET 9, windows, x64 but I suspect any .NET build.
Other information
No response