Gord
Gord

Reputation: 1825

Is it possible to enforce that a type param is nullable on a class

given a class definition like:

public class Test<T>
{
    T _value;

    public void Test(T value)
    {
        _value = value;
    }

    public void DoStuff()
    {
        if(_value.HasValue)
        {
            //stuff
        }
    }
 }

I would like to enforce that T is nullable so I can use the class like:

//does stuff
new Test<int?>(3).DoStuff();
//doesn't do stuff
new Test<int?>(null).DoStuff();

Upvotes: 4

Views: 763

Answers (4)

Martin Peck
Martin Peck

Reputation: 11544

Nullable types are essentially derived from the type Nullable<T>. Could you define your interface based upon Nullable<T>?

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500385

You can't enforce that T itself is a nullable value type, no. You can enforce that T is a non-nullable value type, however - and then use T? everywhere in the class.

public class Test<T> where T : struct
{
    T? _value;

    public void Test(T? value)
    {
        _value = value;
    }

    public void DoStuff()
    {
        if(_value.HasValue)
        {
            //stuff
        }
    }
 }

One other peculiarity is that you can't constrain T to be any nullable type including reference types - and likewise you can't constrain T to be any value type including nullable value types. The where T : class constraint only works with classes (including delegate types) and interfaces, and the where T : struct constraint only with non-nullable value types (including enums).

Upvotes: 6

Adam Ralph
Adam Ralph

Reputation: 29956

You could try:-

public class Test<Nullable<T>>

Upvotes: 0

Joaquim Rendeiro
Joaquim Rendeiro

Reputation: 1388

Yes, just use T? or Nullable<T> as type parameter.

Then your sample becomes:

//does stuff
new Test<int>(3).DoStuff();
//doesn't do stuff
new Test<int>(null).DoStuff();

Upvotes: 0

Related Questions