Roslyn: Handle CallerMemberName gracefully in nullable

Created on 11 Jul 2019  路  5Comments  路  Source: dotnet/roslyn

The cannonical way to use the CallerMemberName attribute is by assigning null as a default value to it, like so:
C# public void M([CallerMemberName] string param = null) { }
But this will produce a warning, because param is declared as having a default value of null, even though the null won't ever actually be used. We should try and support the existing way people write this code, without requiring them to suppress the null.

Area-Compilers Area-Language Design Bug New Language Feature - Nullable Reference Types

Most helpful comment

Seeing that example though, I'm thinking that the current behavior, while unfortunate for some scenarios, is probably correct. If you want to have a defaultValue of null, then you need to ! or declare as nullable.

All 5 comments

Also remember to support param being nullable. In WPF it is common to have:

protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)
{
    this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

And passing null means notify for all properties. Not sure if null and string.Empty has different meanings but chances are there is code relying on it.

@333fred Did we conclude that the proper way of declaring M is public void M([CallerMemberName] string? param = null)?

@jcouv no. The examples on docs.microsoft.com do use "" as the default value, but other than the code examples there is no official guidance on what default value should be used. The question here is a tradeoff I think, because for the scenario that @JohanLarsson outlined above, it would be a bad thing if we didn't warn about string propertyName = null.

Seeing that example though, I'm thinking that the current behavior, while unfortunate for some scenarios, is probably correct. If you want to have a defaultValue of null, then you need to ! or declare as nullable.

From discussion with Mads, the current behavior seems fine. I'll go ahead and close. Thanks

Was this page helpful?
0 / 5 - 0 ratings