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.
Using generics, primitive types can not be passed as type parameters. In the example given below, if we pass int primitive type to box class, then compiler will complain. To mitigate the same, we need to pass the Integer object instead of int primitive type.
To use Java generics effectively, you must consider the following restrictions: Cannot Instantiate Generic Types with Primitive Types.
Generic type arguments are constrained to extend Object , meaning that they are not compatible with primitive instantiations unless boxing is used, undermining performance. With the possible addition of value types to Java (subject of a separate JEP), this restriction becomes even more burdensome.
Definition: “A generic type is a generic class or interface that is parameterized over types.” Essentially, generic types allow you to write a general, generic class (or method) that works with different types, allowing for code re-use.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With