Convert string to generic type c# (Convert string to T)
c#, generics, type-conversion
Solution
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
}
Problem
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.