How to define generic type limit to primitive types?

David.Chu.ca picture David.Chu.ca · Apr 30, 2009 · Viewed 55.3k times · Source

I have the following method with generic type:

T GetValue<T>();

I would like to limit T to primitive types such as int, string, float but not class type. I know I can define generic for class type like this:

C GetObject<C>() where C: class;

I am not sure if it is possible for primitive types and how if so.

Answer

BFree picture BFree · Apr 30, 2009

You can use this to limit it to value types:

where C: struct

You also mention string. Unfortunately, strings won't be allowed as they are not value types.