Jeremy Richards
Jeremy Richards

Reputation: 313

How do you override a nullable annotated generic method in C#?

I am trying to add nullability support to parts of an existing code base. One area that has me stumped is how to override a generic method when the return value is nullable annotated.

#nullable enable
public class Stuff<T> {}

public abstract class Base {
    public virtual Stuff<T?>? MakeStuff<T>() => null;
    
    public Stuff<T?>? MakeStuff2<T>() => null;  
}


public abstract class Derived : Base {
    public override  Stuff<T?>? MakeStuff<T>() => base.MakeStuff<T>();
}

This results in a pair of error messages that don't quite make sense to me:

Compilation error (line 26, col 29): 'Derived.MakeStuff()': return type must be 'Stuff<T?>' to match overridden member 'Base.MakeStuff()'

Compilation error (line 26, col 29): The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable'

This all works when nullable is not enabled.

Upvotes: 10

Views: 1282

Answers (1)

Jeremy Richards
Jeremy Richards

Reputation: 313

Thanks to @Emanuel’s comment, which pointed me in the right direction.

The answer is to use the where T:default constraint, which solves the issue in C# 9 and above.

Upvotes: 6

Related Questions