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

Viewed 25344
  • 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); }
4 Answers

I think the example below covers a lot of use cases that one would expect from ValueType. The parameter type of T? allows nullables, and the type constraints restrict it to structs that implement IFormattable which is true for the common value types I can think of.

public void foo<T>(T? a) where T : struct, IFormattable

Note that this allows types such as decimal, datetime, timespan.

https://docs.microsoft.com/en-us/dotnet/api/system.iformattable?view=netcore-3.1

Related