Monday, November 23, 2009

Configuration Helpers

This post is mainly so I’ll be able to find this code later.

I’ve been on multiple projects that make heavy use of configuration and I always end up writing these helpers similar to the ones listed below. These are general conversion routines that take a String and try to cast it to a specified value. In this version, I’ve included a special case when casting to Boolean. A “1” is considered TRUE and “0” FALSE.

 

public bool TryCastFromStringTo<T>(string s, out T value) 
{
value = default(T);
if (typeof(T) == typeof(bool))
{
if (s.Trim() == "1")
{
value = ((T)(object)true);
return true;
}
if (s.Trim() == "0")
{
value = ((T)(object)false);
return true;
}
}

TypeConverter converter = TypeDescriptor.GetConverter(typeof(T));
object convertedValue;
try
{
convertedValue = converter.ConvertFromString(s);
}
catch (Exception e)
{
if (e is NotSupportedException
|| e is InvalidCastException || e is FormatException)
{
return false;
}
if (null != e.InnerException && e.InnerException is FormatException)
{
return false;
}
throw;
}
value = (T) convertedValue;
return true;
}

public T SafelyCastFromStringTo<T>(string value, T defaultValue)
{
if (null == value) return defaultValue;
T convertedValue;
if (this.TryCastFromStringTo(value, out convertedValue))
{
return convertedValue;
}
return defaultValue;
}

No comments:

Post a Comment