Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a value based on the type of the generic T

I have a method like:

public T Get<T>(string key)
{

}

Now say I want to return "hello" if the type is a string, and 110011 if it is type int.

how can I do that?

typeof(T) doesn't seem to work.

I ideally want to do a switch statement, and return something based on the Type of the generic (string/int/long/etc).

Is this possible?

like image 803
Blankman Avatar asked Nov 28 '22 19:11

Blankman


1 Answers

The following should work

public T Get<T>(string key) { 
   object value = null;
   if ( typeof(T) == typeof(int) ) { 
     value = 11011;
   } else if ( typeof(T) == typeof(string) ) { 
     value = "hello";
   }
   return (T)value;
}
like image 137
JaredPar Avatar answered Dec 10 '22 06:12

JaredPar