- Why can’t I use a constraint of
where T : System.ValueType? - Why does Microsoft prevent this type
from being a constraint?
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 struct over ValueType?
// Defined in my class
public void foo<T>(T a) where T : struct
{ bar<T>(a); }
There are two differences between using
and
Tto beValueTypeitself, which is a reference type.Tto be a nullable value typeThe first of these differences is almost never what you want. The second could occasionally be useful;
Nullable<T>is slightly odd in that it satisfies neither thewhere T : structnorwhere T : classconstraint.More useful would be the constraint
which is prohibited by C# for no good reason that I can tell. See my blog post and the Unconstrained Melody project for more on this.