Consider the following:
private T getValue<T>(String attr)
{ ... }
How do I check to see what Type is?
I was thinking of:
if("" is T) // String
if(1 is T) // Int32
Is there a better way?
The short answer is, that there is no way to find out the runtime type of generic type parameters in Java. A solution to this is to pass the Class of the type parameter into the constructor of the generic type, e.g.
If you call the GetGenericTypeDefinition method on a Type object that already represents a generic type definition, it returns the current Type. An array of generic types is not itself generic. In the C# code A<int>[] v; or the Visual Basic code Dim v() As A(Of Integer) , the type of variable v is not generic.
In this article. The where clause in a generic definition specifies constraints on the types that are used as arguments for type parameters in a generic type, method, delegate, or local function. Constraints can specify interfaces, base classes, or require a generic type to be a reference, value, or unmanaged type.
C# allows you to use constraints to restrict client code to specify certain types while instantiating generic types. It will give a compile-time error if you try to instantiate a generic type using a type that is not allowed by the specified constraints.
There's the function typeof(T)
?
You can use the function typeof(T)
?
So to check for the string, do
if(typeof(T) == typeof(string))
// do something
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