tags:

views:

106

answers:

4

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

But I am sure there is a better way!

-Theo

+6  A: 

There's the function typeof(T)?

Unsliced
so if(typeof(T) == Type.GetType("String"))???
Theofanis Pantelides
if(typeof(T) == typeof(String)) should be faster
helium
+2  A: 

You can use the function typeof(T)?

So to check for the string, do

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

Marco Spatz
+4  A: 

This is almost certainly a flaw in the design of your function if you need to get the type of the generic type parameter; This is opposite of “generic”. Hence, use overloading instead.

Other than that, Unsliced has already given the correct answer of determining the type of T.

Konrad Rudolph
I need it for debugging purposes.
Theofanis Pantelides
+1  A: 

There are actually 2 methods doing that, if the expected classes derive from the same class or interface or abstract class you can do easly in the Generic Signature

T GetValue() where T : class, this will force whole T Types To Be Reference Types. Or T GetValue() where T : IDisposable , this will force whole T Types to implement IDisposable.

for your case typeof(T) will solve your problems, but in this case, make the method not generic.

Kerem Kusmezer