Search code examples
c#genericsinterfacenullable

Generic property type in intercace and nullable error


Non generic interface has no issue with nullable mark. In generic interface below marking TKey as nullable generates compiler error. Why ? And is it possible to mark generic property type as nullable ?

Error CS0738 'TClass' does not implement interface member 'ITest.Info1'. 'TClass.Info1' cannot implement 'ITest.Info1' because it does not have the matching return type of 'int'.

    public interface ITest<TKey>
{
    public TKey? Info1 { get; set; }
    public BHPGuard.Domain.LocationType.LocationType? Type { get; set; }

}

public class TClass : ITest<int>
{
    public int? Info1 { get; set; }
    public LocationType.LocationType? Type { get; set; }
    // int ITest<int>.Info1 { get; set; }
}

Solution

  • Why ?

    The problem here is that TKey is unconstrained generic type, so for value types TKey? is TKey, so to implement the interface you can do:

    public class TClass : ITest<int>
    {
        public int Info1 { get; set; }
        public LocationType? Type { get; set; }
    }
    

    or

    public class TClass : ITest<int?>
    {
        public int? Info1 { get; set; }
        public LocationType? Type { get; set; }
    }
    

    Alternatively you can constrain the generic parameter to be a struct:

    public interface ITest<TKey> where TKey : struct
    {
        public TKey? Info1 { get; set; }
        // ...
    }
    

    is it possible to mark generic property type as nullable ?

    Yes, but due to the difference of how nullable reference and nullable value types are treated (the later are actually represented via type Nullable<T> while former are not) it has quite some limitations in terms of how it will behave depending on the constraints defined.

    See Nullability and generics in .NET 6 and Why does nullability check not work with value types? for more info.