I found myself writing the following code this evening:
public T GetItem<T>(string name)
{
string result = node.SelectSingleNode(name).InnerText.Trim();
return (T)GetConverter(typeof(T)).ConvertFromString(result);
}
private TypeConverter GetConverter(Type objectType)
if (objectType.Equals(typeof(int)))
return new Int32Converter();
else if (objectType.Equals(typeof(bool)))
return new BooleanConverter();
else if (objectType.Equals(typeof(string)))
return new StringConverter();
else
throw new ArgumentException("Does not support casting to " + objectType.Name);
Don't ever write code like this. Read the documentation which explicitly says that "you should never create an instance of a BooleanConverter". If you follow their advice, your code will become much cleaner. Like so:
return (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromString(result);
Page rendered at Tuesday, December 02, 2008 6:33:48 AM (Central Standard Time, UTC-06:00)
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.