Search code examples
c#.netgenericsnullable

Is there a way to define an generic interface with a constraint that the type can be null (but cannot be a value type)?


I'd like to define an generic interface that allows nullable value types (int?, double?, etc.) and class types (which can also be null). I do not want to allow a simple value type. Is there a way to do this?


Solution

  • EDIT: Given the question title, I assume you want to constrain the type parameter to not be a non-nullable value type. It would probably be a good idea to specify that in the question body too.

    No - there's no such constraint. In fact, both class and struct constraints prohibit arguments which are nullable value types.

    You could potentially create an interface without a constraint, but only create two implementations:

    interface IFoo<T> { }
    
    class FooClass<T> : IFoo<T> where T : class {}
    
    class FooNullableValue<T> : IFoo<Nullable<T>> where T : struct {}
    

    That wouldn't stop anyone else from implementing IFoo<int> of course. If you can give us more background, we may be able to help more.