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
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
You can use the function typeof(T)
?
So to check for the string, do
if(typeof(T) == typeof(string))
// do something
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
.
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.