C# Dynamic Type Conversions

I’ve been looking at ways of parsing types and values from text without having to do switch/case statements or explicit casting.  So far, based on my understanding of statically typed languages, is that this is impossible with a statically typed language.

<Question> Is this really true?</Question>

Given my current knowledge, my way of bypassing this is to use the new dynamic type in .NET 4.  It allows me to implicitly assign an object without having to cast it.  It works by bypassing the type checking at compile time.

Here’s a fairly straightforward example:

static void Main(string[] args)
{
	Type boolType = Type.GetType("System.Boolean");
	Console.WriteLine(!parse("true", boolType));

	Type dateTimeType = Type.GetType("System.DateTime");

	DateTime date = parse("7/7/2010", dateTimeType);
	Console.WriteLine(date.AddDays(1));

	Console.ReadLine();
}

static dynamic parse(string value, Type t)
{
	return Convert.ChangeType(value, t);
}

Now, if I were to do something crazy and call

DateTime someDate = parse(“1234”, Type.GetType(“System.Int32”));

a RuntimeBinderException would be thrown because you cannot implicitly convert between an int and a DateTime.

It certainly makes things a little easier.