Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 326
David.Chu.ca Avatar asked Apr 30 '09 03:04

David.Chu.ca


People also ask

Can generics be used for primitive types?

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.

Can you substitute a generic type with a primitive data type?

To use Java generics effectively, you must consider the following restrictions: Cannot Instantiate Generic Types with Primitive Types.

Why are primitives not possible as generic 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.

How do you define generic type?

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.


2 Answers

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.

like image 197
BFree Avatar answered Oct 22 '22 04:10

BFree


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

like image 28
Deko Avatar answered Oct 22 '22 02:10

Deko