Type exception in general constraints (maybe?)

Is it possible to exclude certain types from the set of possible types that can be used in a common parameter? If so, how.

for example

Foo<T>() : where T != bool 

will mean any type except bool type.

Edit

Why?

The following code is my attempt to enforce a negative constraint.

 using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { var x1=Lifted.Lift("A"); var x2=Lifted.Lift(true); } static class Lifted { // This one is to "exclude" the inferred type variant of the parameter [Obsolete("The type bool can not be Lifted", true)] static public object Lift(bool value) { throw new NotSupportedException(); } // This one is to "exclude" the variant where the Generic type is specified. [Obsolete("The type bool can not be Lifted", true)] static public Lifted<T> Lift<T>(bool value) { throw new NotSupportedException(); } static public Lifted<T> Lift<T>(T value) { return new Lifted<T>(value); } } public class Lifted<T> { internal readonly T _Value; public T Value { get { return this._Value; } } public Lifted(T Value) { _Value = Value; } } } } 

As you can see, this is due to some belief in the correct resolution of the overload and the @jonskeet -esque evil code bit.

Comment on the suggestion section of the proposed type and it doesn't work.

It would be much better to have an excluded general restriction.

+8
generics c # constraints
source share
2 answers

No, you cannot make one-time exceptions like these using type restrictions. You can do this at runtime:

 public void Foo<T>() { if (typeof(T) == typeof(bool)) { //throw exception or handle appropriately. } } 
+4
source share

It sounds like an aspect of the program. You might want to consider Aspect Oriented Programming to provide this limitation at compile time.

PostSharp should provide this feature.

0
source share

All Articles