Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic class accepts primitive type and string

How do i create a generic type which accepts only a type of Integer, Long and String.

I know we can restrict a type for a single class or by implementing an interface with below code

public class MyGenericClass<T> where T:Integer{ }

or to handle int,long but not string

public class MyGenericClass<T> where T:struct 

Is it possible to create a generic which accepts only a type of Integer, Long and String?

like image 972
Billa Avatar asked May 14 '13 11:05

Billa


People also ask

Can primitive types be used in generics?

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 primitive types be used in generics Java?

So, anything that is used as generics has to be convertable to Object (in this example get(0) returns an Object ), and the primitive types aren't. So they can't be used in generics.

What do you need to use if you want to use primitive types in a generic class type variable?

Java generics have the restriction that they must be instantiated with a user-defined class. Hence generics may not be instantiated with primitive types, such as ints. If you want to use a primitive type, use its wrapper type instead, such as Integer.

Do generics work with primitives typescript?

Using generics allows us to write a typesafe code that will work with a wide range of primitives and objects.


1 Answers

You could potentially not have the constraints in the class declaration, but do some type-checking in a static constructor:

public class MyGenericClass<T>
{
    static MyGenericClass() // called once for each type of T
    {
        if(typeof(T) != typeof(string) &&
           typeof(T) != typeof(int) &&
           typeof(T) != typeof(long))
            throw new Exception("Invalid Type Specified");
    } // eo ctor
} // eo class MyGenericClass<T>

Edit:

As Matthew Watson points out above, the real answer is "You can't and shouldn't". If your interviewer believes that to be incorrect, then you probably don't want to work there anyway ;)

like image 94
Moo-Juice Avatar answered Oct 27 '22 19:10

Moo-Juice