I have not played much with orcas or .NET 3.5 but had an interesting idea so had to crack and get it up and running.
One thing I have not liked is having to cast/parse types as it leads to harder to read code in some situations . i.e.:
int myInt = int.Parse(((customer)value).SocialInsuranceNumber)
or
dim myInt as integer = integer.Parse(ctype(value, customer).SocialInsuranceNumber)
So playing around with extension methods I got code like this that is a bit more fluent:
int myInt = value.CastTo<customer>().SocialInsuranceNumber.Parse<int>();
I find this a lot more readable. Here is the code:
public static class CastExtension
{
public static T CastTo<T>(this object value)
{
if (value == null) throw new ArgumentNullException("can not cast a null value");
return (T)value;
}
public static int ToInt(this object value)
{
if (value == null) throw new ArgumentNullException("can not cast a null value");
return int.Parse(value.ToString());
}
public static T Parse<T>(this object value)
{
T parser = (T)Activator.CreateInstance(typeof(T));
System.Reflection.MethodInfo mi = parser.GetType().GetMethod("Parse", new Type[] { typeof(String) });
if (mi == nothing) throw new ApplicationException("can not parse on a type that does not implement Parse(string)");
return (T)mi.Invoke(parser, new Object[] { value });
}
}
I hate the implementation of the parse method but until I find a better way... it works. I wish that the type.Parse() methods implemented a generic interface or something along those lines as I had to use reflection to execute the Parse() method on the objects. I also implemented a ToInt() extension for an example as well so that it did not have to use reflection but I figured this would get quite chatty to implement all the different type conversions.