I have to wonder what the real intent of the question is... Is the Get
method supposed to retrieve a value of the specified key
from some kind of storage? In that case, I would imagine something like
public T Get<T>(string key)
{
// GetValue(key) returns a value of type object.
return (T)_storage.GetValue(key);
}
would be more appropriate. The answers proposed so far make no use of the key
parameter at all (I suppose that is legitimate, given that the original question seeks to hard code some kind of return value based on the type of T
, regardless of what key
represents).
You normally use generics to provide a generic behavior regardless of the type you're dealing with. If you start introducing a switch
statement to modify behavior based on the Type
of the method, you likely aren't using generics properly, and/or you should look into implementing separate, type-specific methods.