C# – How to define generic type limit to primitive types


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.

Best Solution

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.