Skip to content

Nullable<T>.ToString() should return null when there is no value #120706

@ehorrent

Description

@ehorrent

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:

  1. Get a null value:

ToString() returns null when there is no value:

public override string? ToString() => hasValue ? value.ToString() : null;
  1. 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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions