How to return a value based on a type of common T

I have a method like:

public T Get<T>(string key)
{

}

Now say that I want to return “hello” if the type is a string, and 110011 if it is an int.

How can i do this?

typeof (T) doesn't seem to work.

Ideally, I want to make a switch statement and return something based on the generic type (string / int / long / etc).

Is it possible?

+3
source share
5 answers

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;
}
+7
source

I need to wonder what the real purpose of the question is. Is there a method Getto get the value specified keyfrom some store? In this case, I would suggest something like

public T Get<T>(string key)
{
    // GetValue(key) returns a value of type object.
    return (T)_storage.GetValue(key);
}

. , , key ( , , , - T, , key).

generics , . switch , Type , , , / , .

+3

, .

, "" , . , , ... .

, , , , , .

+3

T , . , :

int x = obj.Get<int>("key");

, object? :

int x = (int)obj.Get("get");
+2

switch Type, , , , , , Type, . .

+2
source

Source: https://habr.com/ru/post/1750310/


All Articles