C # generic does * not * implement something

I know I can make a method like

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

Is it possible to do the opposite, 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 at all.

+4
source share
3 answers

No, in general, you cannot specify an โ€œexception listโ€. However, to prevent the validity of Nullable types, you can use the "where T: class" constraint. Because Nullable is a structure that will have the desired effect.

Edit: Oh, it looks like I was too hasty - you asked how to forbid to allow anything that could be empty or, in particular, Nullable?

0
source

If you do not want to use types with a null value, you can do this.

 private T MyFun<T>() where T : struct {...} 
+2
source

You can always just throw a NotSupportedException () at runtime. Admittedly, this is not as good as a compiler preventing it

0
source

All Articles