tags:

views:

127

answers:

3

I want to restrict the generic type parameter to:

1) either that of a certain user defined reference type;

OR

2) any of the primitive types in the CLR;

How do I say something to the effect of:

interface IDataManager<T>: IDataManager
    where T: IDataObject, T: ValueType
+1  A: 

From Constraint cannot be special class 'System.Enum'

More investigation shows the C# 2.0 specification to have the following comments on constraints:

A class-type constraint must satisfy the following rules:

  • The type must be a class type.
  • The type must not be sealed.
  • The type must not be one of the following types: System.Array,
    System.Delegate, System.Enum, or
    System.ValueType.
  • The type must not be object. Because all types derive from object, such a constraint would have no effect if it were permitted.
  • At most one constraint for a given type parameter can be a class type.

Also Compiler Error CS0702

And mentioned at

Jon Skeet: Coding Blog : Generic constraints for enums and delegates

astander
+1  A: 

There's no constraint you can use that limits you to the built-in primitives. What I would do to get around that is overload the method for each primitive, and perhaps have each overload simply pass it's argument to a private generic method that holds the common code.

Joel Coehoorn
+1  A: 
T: ValueType 

The closest you can get is T : struct, but that wouldn't limit it only to CLR types. Either way, I don't believe there is a way to have an OR generic constraint. You could have one generic method and n-overloads for specific types.

You also can not, for example, define multiple generic functions differing only in their constraints. Constraints are not part of the signature. See: http://blogs.msdn.com/ericlippert/archive/2009/12/10/constraints-are-not-part-of-the-signature.aspx

Anthony Pegram