C# – Cast with GetType()

ccastingreflection

Is it possible to cast an object to the type returned from GetType()? I'd like a generic method that can accept an object (for anonymous types) but then return an object cast as the anonymous type. I've been thinking of using the LCG DynamicMethod to build a method on a container class, but I can't exactly figure out what that would look like. The idea to cast with the GetType() method was to be able to get the anonymous type and cast an object to its actual type without actually knowing the type.

The overarching goal is to stick anonymous-typed objects into a container, that I could then share and pass between methods.

Best Answer

I can't think of why you'd want to cast as GetType(), because you wouldn't be able to do anything to useful with the result, without knowing the type at compile time anyway.

Perhaps what you are looking for, is being able to Convert. If that is the case, the following should work for you:

object input = GetSomeInput();
object result = Convert.ChangeType(input, someOtherObject.GetType());

We use this when reading values from the registry which are all stored as strings, and then stuffing them into properties using reflection.