SkillGG
SkillGG

Reputation: 686

How to ensure a generic parameter is not Nullable?

I am trying to make a class GameOption that will hold three (really four) values:

This how looks my class:

public class GameOption<T> {
    private T v;
    private string n;
    private T? def;
    public string Name { get => this.n; }
    public T Value { get => this.v; }
    public GameOption(T o, string name, T? def) {
        this.n = name;
        this.v = o;
    }
    public void ChangeValue(T o) {
        this.v = o;
    }
}

But there is a problem. T cannot be Nullable as VS says:

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

How do I make sure that T is not Nullable?

Is there something like class X<@NotNull T> or what?

Upvotes: 1

Views: 1643

Answers (2)

jeancallisti
jeancallisti

Reputation: 1681

Nowadays :

public class GameOption<T> where T : notnull { }

Upvotes: 7

JSteward
JSteward

Reputation: 7091

To ensure the type T is not nullable constrain it to a struct:

public class GameOption<T> where T : struct { }

Generic Constraints

Upvotes: 6

Related Questions