My conversion extensions which allow you to do:
int i = myString.To();
Here it is, as posted on TheSoftwareJedi.com
public static T To(this IConvertible obj)
{
return (T)Convert.ChangeType(obj, typeof(T));
}
public static T ToOrDefault
(this IConvertible obj)
{
try
{
return To(obj);
}
catch
{
return default(T);
}
}
public static bool ToOrDefault
(this IConvertible obj,
out T newObj)
{
try
{
newObj = To(obj);
return true;
}
catch
{
newObj = default(T);
return false;
}
}
public static T ToOrOther
(this IConvertible obj,
T other)
{
try
{
return Toobj);
}
catch
{
return other;
}
}
public static bool ToOrOther
(this IConvertible obj,
out T newObj,
T other)
{
try
{
newObj = To(obj);
return true;
}
catch
{
newObj = other;
return false;
}
}
public static T ToOrNull
(this IConvertible obj)
where T : class
{
try
{
return To(obj);
}
catch
{
return null;
}
}
public static bool ToOrNull
(this IConvertible obj,
out T newObj)
where T : class
{
try
{
newObj = To(obj);
return true;
}
catch
{
newObj = null;
return false;
}
}
You can ask for default (calls blank constructor or "0" for numerics) on failure, specify a "default" value (I call it "other"), or ask for null (where T : class). I've also provided both silent exception models, and a typical TryParse model that returns a bool indicating the action taken, and an out param holds the new value.
So our code can do things like this
int i = myString.To();
string a = myInt.ToOrDefault();
//note type inference
DateTime d = myString.ToOrOther(DateTime.MAX_VALUE);
double d;
//note type inference
bool didItGiveDefault = myString.ToOrDefault(out d);
string s = myDateTime.ToOrNull();
I couldn't get Nullable types to roll into the whole thing very cleanly. I tried for about 20 minutes before I threw in the towel.