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.
Solution 1:
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.
Solution 2:
Actually this does the job to certain extend:
public T Object<T>() where T :
struct, IComparable, IFormattable, IConvertible, IComparable<T>, IEquatable<T>
To limit to numeric types you can get some useful hints of the following samples defined for the ValueType class
Solution 3:
Here's what you're looking for:
T GetObject<T>() where T : struct;