Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find Type of Type parameter [duplicate]

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?

like image 436
Theofanis Pantelides Avatar asked Mar 01 '10 12:03

Theofanis Pantelides


People also ask

How do I get a class instance of generic type T?

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.

How to get generic type in c#?

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.

Which keyword is used to apply constraints on type parameter?

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.

What is a constraint c#?

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.


2 Answers

There's the function typeof(T)?

like image 100
Unsliced Avatar answered Sep 20 '22 18:09

Unsliced


You can use the function typeof(T)?

So to check for the string, do

if(typeof(T) == typeof(string)) // do something

like image 31
Marco Spatz Avatar answered Sep 21 '22 18:09

Marco Spatz