Nullability Mismatch Between Property Getter and Setter?

39 views Asked by At

I've written a class that implements IDataParameter in C# with .NET 8. I get CS8767 on the Setter for this code:

public class TestDataParameter: IDataParameter
{
   ...

   public string ParameterName
   {
      get; set;
   } = "";
   ...
}

Making the return type string? leads to CS8766 on the Getter.

public class TestDataParameter: IDataParameter
{
   ...

   public string? ParameterName
   {
      get; set;
   } = "";
   ...
}

This is extremely annoying. The interface declares the property as string. I don't understand why it would need different nullabilities for the getter and the setter and how this should be implemented. IDataParameter declares string ParameterName { get; set; } so implementing the property non-nullable should be right. Does anyone have any idea why this happens and how to deal with it correctly? Thanks, Alex.

1

There are 1 answers

0
Guru Stron On BEST ANSWER

If you want to remove the warning you can follow the approach which the interfaces uses itself - use the AllowNullAttribute:

public class TestDataParameter : IDataParameter
{
    // ...
    [AllowNull]
    public string ParameterName { get; set; } = "";
    // ...
}

You might want though to switch from the auto-property implementation to one which will maintain the contract (i.e. you can pass null but null is never returned as for example OdbcParameter does):

private string? _parameterName = "";

[AllowNull]
public string ParameterName
{
    get => _parameterName ?? string.Empty;
    set => _parameterName = value;
}

See also: