I’m aware that questions like this have been asked before and I doubt it’s possible, but I just wanted to make 100% sure that it isn’t.
In VB.net or C# (either language, it doesn’t matter), I want to cast a variable to a type represented by another Type variable. Here’s an example of the kind of code that would be needed in C#:
Object castMe = new Foo();
Type castTo = typeof(Foo);
Foo beenCast = (castTo.GetRepresentedType())castMe;
beenCast.MethodInFoo();
… or in VB, something like:
Dim castMe As Object = New Foo()
Dim castTo As Type = GetType(Foo)
Dim beenCast As Foo = CType(castMe, castTo.GetRepresentedType())
beenCast.MethodInFoo()
The big problem is obviously specifying a method which will return a Type at runtime for the cast type argument, rather than an actual compile-time type (ie. CType(castMe, Foo)). I don’t quite understand why you can’t do this, though… sure, runtime cast errors may result, but you can also get them when you DO specify a compile-time type. If castMe is not an instance of Foo, then even CType(castMe, Foo) will still throw an InvalidCastException.
If you do know to which type you want to cast you will have to end up with something like this:
T is now your type argument.
If you don’t know what the type is that you cast to, the compiler can’t know either. That’s a statically typed language for you. If you don’t like such things you may want to have a wander through e.g. ruby.
In cases like that, usual responses are abstactions via base classes or interfaces – extract common behaviour into properties, events and methods that can be used in a statically typed language, even though you don’t know the specific type in a given situation.