Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to generic type c# (Convert string to T) [closed]

I have a method that needs to convert a string to the generic type:

T GetValue<T>(string name)
{
   string item = getstuff(name);
   return item converted to T   // ????????
}

T could be int or date.

like image 671
Ian Vink Avatar asked Feb 16 '14 05:02

Ian Vink


1 Answers

you can use Convert.ChangeType

T GetValue<T>(string name)
{
   string item = getstuff(name);
   return (T)Convert.ChangeType(item, typeof(T));
}

if you need to limit input types only for int and DateTime, add condition like below

if (typeof(T) != typeof(int) && typeof(T) != typeof(DateTime))
{
     // do something with other types 
}
like image 91
Damith Avatar answered Oct 02 '22 15:10

Damith