tags:

views:

107

answers:

3

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.

+2  A: 

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

private T MyFun<T>() 
  where T : struct
{...}
ChaosPandion
A: 

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
Let's assume for hypothetical purposes he wants to prevent `Nullable<T>` from being used. With the constraint `T : class`, you've excluded *all* structs, not only `Nullable<T>`.
Anthony Pegram
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<T>. Admittedly, it's less than ideal - as you've noticed!
Ben
@Ben: Interestingly enough, the `where T : struct` constraint *also* excludes `Nullable<T>`. So if the OP knows for sure he/she wants only value types or reference types, one of these will work.
Dan Tao
@Ben: 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
A: 

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

erash