Convert string to T

I have a method that should convert a string to a generic type:

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

T can be int or date.

+4
source share
1 answer

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 restrict input types to int and DateTime only, add a condition like below

if (typeof(T) != typeof(int) && typeof(T) != typeof(DateTime))
{
     // do something with other types 
}
+11
source

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


All Articles