Why can't I use System.ValueType as a generics constraint?

  • Why can't I use the where T : System.ValueType constraint?
  • Why does Microsoft prevent this type from limiting?



Example:

Why can't I do the following?

 // Defined in a .Net class public void bar<T>(T a) where T : ValueType {...} // Defined in my class public void foo<T>(T a) where T : ValueType { bar<T>(a); } 

What is the difference in using structure over ValueType?

 // Defined in my class public void foo<T>(T a) where T : struct { bar<T>(a); } 
+43
generics c #
Dec 06 '09 at 7:15
source share
3 answers

There are two differences between using

 where T : struct 

and

 where T : ValueType 
  • the latter might T be a ValueType itself, which is a reference type.
  • the latter would also allow T a value type with a zero value

The first of these differences is almost never what you want. This can sometimes be useful; Nullable<T> bit odd in that it satisfies neither the where T : struct nor where T : class constraint.

A more useful limitation would be

 where T : struct, System.Enum 

which is forbidden by C # for any good reason I can say. See my blog post and Non Tune Design for more information on this.

+60
Dec 06 '09 at 8:21
source share

ValueType is not a base class of value types; it simply represents a container for a value when it is placed in a box. Since this is a container class, not any hierarchy for the actual types you want to use, this is not useful as a general restriction.

+12
Dec 06 '09 at 7:19
source share

Using struct as a general constraint is functionally equivalent to a "ValueType" constraint. In .NET, struct is a value type .

+6
Dec 06 '09 at 7:25
source share



All Articles