4

I know I can make a method like

private T MyFun<T>() 
  where T : IMyInterface
{...}

Can I do the reverse, i.e. where T does not implement IMyInterface? The specific use case is that I don't want to allow nullables, but I'm curious just in general.

Xodarap
  • 11,581
  • 11
  • 56
  • 94
  • Even if you *could* exclude a particular *interface* (or base type), how would you use that to exclude `Nullable` for any `T`? Even with this feature, you can’t do that. – Timwi Oct 01 '10 at 20:14

3 Answers3

2

If you don't want nullable types you can do this.

private T MyFun<T>() 
  where T : struct
{...}
ChaosPandion
  • 77,506
  • 18
  • 119
  • 157
0

No, in the general case you cannot specify an "exclusion list". However, to prevent Nullable types from being allowed, you can use the "where T : class" constraint. Because Nullable is a struct, that will have the desired effect.

Edit: Oops, it appears that I was too hasty - were you asking how to prevent anything that can be null, or specifically Nullable, from being allowed?

Ben
  • 6,023
  • 1
  • 25
  • 40
  • Let's assume for hypothetical purposes he wants to prevent `Nullable` from being used. With the constraint `T : class`, you've excluded *all* structs, not only `Nullable`. – Anthony Pegram Oct 01 '10 at 19:56
  • True - as stated, there is no such thing as an "exclusion list" constraint. This is the only way, with generic constraints, that I know of to exclude Nullable. Admittedly, it's less than ideal - as you've noticed! – Ben Oct 01 '10 at 20:01
  • Interestingly enough, the `where T : struct` constraint *also* excludes `Nullable`. So if the OP knows for sure he/she wants only value types or reference types, one of these will work. – Dan Tao Oct 01 '10 at 20:08
  • My question was about nullables, but I was really more curious about the general statement. And the answer to that it sounds like is that you can't exclude some. – Xodarap Oct 01 '10 at 20:11
0

You could always just throw a NotSupportedException() at run-time. Admittedly, not as nice as the compiler preventing it

cordialgerm
  • 8,403
  • 5
  • 31
  • 47