Leslie Hanks
Leslie Hanks

Reputation: 2377

How to specify types not allowed in a .NET Generics constraint?

Is it possible to specify a constraint on a generic class that disallows certain types? I don't know if it is possible and if it is, I am not sure what the syntax would be. Something like:

public class Blah<T> where : !string {
}

I can't seem to find any notation that would allow such a constraint.

Upvotes: 13

Views: 3293

Answers (4)

Dan Tao
Dan Tao

Reputation: 128447

The closest you can get is a run-time constraint.

Edit: Originally I put the run-time check in the constructor call. That's actually not optimal, as it incurs overhead on every instantiation; I believe it would be much more sensible to put the check in the static constructor, which will be invoked once per type used as the T parameter for your Blah<T> type:

public class Blah<T> {
    static Blah() {
        // This code will only run ONCE per T, rather than every time
        // you call new Blah<T>() even for valid non-string type Ts
        if (typeof(T) == typeof(string)) {
            throw new NotSupportedException("The 'string' type argument is not supported.");
        }
    }
}

Obviously not ideal, but if you put this constraint in place and document the fact that string is not a supported type argument (e.g., via XML comments), you should get somewhere near the effectiveness of a compile-time constraint.

Upvotes: 12

Peter Kelly
Peter Kelly

Reputation: 14411

Here are the allowed constraints (more detail)

  • where T: struct
  • where T : class
  • where T : new()
  • where T : [base class name]
  • where T : [interface name]
  • where T : U (The type argument supplied for T must be or derive from the argument supplied for U)

Upvotes: 1

jakebasile
jakebasile

Reputation: 8132

Constraints can only be positive constraints, as outlined in the documentation.

The only thing you can do is specify what types can be put into the generic type, but you cannot specify what can't be put into them.

Upvotes: 2

Donut
Donut

Reputation: 112915

No, you can't directly specify "negated" type constraints.

Upvotes: 4

Related Questions