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?

0

2 Answers 2

7

Nowadays :

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

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

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

Generic Constraints

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.