jeudi 25 août 2016

Casting Using a Variable of Type 'Type' Instead of Type Name

First I should mention it seems like this will be a duplicate, but I can't seem to find the question pertaining to this specific problem. I only found close ones that don't address this specific approach and are thus not useful.

Consider this scenario where I'd like to cast something to a type. I might do something like one of these:

var foo = GetInstanceOfSomeUnknownType();
var cast1 = (MyCustomType)foo;
var cast2 = foo as MyCustomType;

Not let's consider what to do if, for whatever reason, we can't directly cast using the name MyCustomType. The below doesn't work:

var foo = GetInstanceOfSomeUnknownType();
var bar = "Whatever.";
Type someType = foo.GetType();
var cast1 = (someType)bar;
var cast2 = bar as someType;

In essence, you can do these sorts of casts using the type name, but not with a Type variable representing that type. I'd like to cast something using a Type object of the type I want to cast to instead of its name. Is there a way around this?





Aucun commentaire:

Enregistrer un commentaire