1

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

  • Name of Option as string

  • An option as T

  • A default value as Nullable< T >

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?

SkillGG
  • 647
  • 4
  • 18

2 Answers2

7

Nowadays :

public class GameOption<T> where T : notnull { }
jeancallisti
  • 1,046
  • 1
  • 11
  • 21
6

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

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

Generic Constraints

JSteward
  • 6,833
  • 2
  • 21
  • 30