My task is to write a method StringToType() that converts a string to the specified type T.
- For primitive types, I use the method Convert.ChangeType()
- For enum-types - Enum.TryParse()
- For all other custom types, I created an interface "IConvertibleFromString" that contains a method "FromString()" to convert the string to the specified type. Any class that will need to convert from string must implement this interface.
But me do not like the way I implemented method StringToType(). I would like to use less than the reflection and ensure as much as possible the performance.
Please advise how best to implement/change it.
class Program
{
static bool StringToType<T>(string str, ref T value)
{
Type typeT = typeof(T);
bool isSuccess = false;
if (typeT.GetInterface("IConvertibleFromString") != null)
{
return (bool)typeT.GetMethod("FromString").Invoke(value, new object[] { str });
}
else if (typeT.IsEnum)
{
MethodInfo methodTryParse = typeT.GetMethod("TryParse").MakeGenericMethod(typeT);
return (bool)methodTryParse.Invoke(null, new object[] { str, value });
}
else if (typeT.IsPrimitive)
{
value = (T)Convert.ChangeType(str, typeT);
return true;
}
return isSuccess;
}
static void Main(string[] args)
{
string intStr = "23";
int val1 = 0;
bool res = StringToType<int>(intStr, ref val1);
Class1 c1;
res = StringToType<Class1>(intStr, ref c1);
Console.ReadKey();
}
}
interface IConvertibleFromString
{
bool FromString(string str);
}
class MySomeClass : IConvertibleFromString
{
int someVal;
public bool FromString(string str)
{
return int.TryParse(str, out someVal);
}
}
if (typeT.GetInterface("IConvertibleFromString") != null) { return (bool)typeT.GetMethod("FromString").Invoke(value, new object[] { str }); }you can dovar iface = value as IConvertibleFromString; if (iface != null) return iface.FromString(str);. That will save you the reflection penalty