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
.