2

I have a Type variable and I need to cast another object to it. (one which I know what the type is, but currently its an "object" type). I need to do this for reasons that aren't really important to the answer.

// Pseudocode
MyObjectClass myTypedVar = new MyObjectClass();

Type myKnownType = myTypedVar.GetType();

var anotherObject = (myKnownType) anObjectVarThatIsReallyMyObjectClass;

I've read this page Type Casting an Object using a "Type" Object in C# and I understand but I don't think it applies directly. I anticipate a solution using reflection, but I just haven't been able to figure it out myself.

CarComp
  • 1,929
  • 1
  • 21
  • 47

1 Answers1

3

If I understand you correctly, you could use the Convert.ChangeType method:

var anotherObject = Convert.ChangeType(anObjectVarThatIsReallyMyObjectClass, myKnownType);

You won't get any kind of compile-time checking when using a dynamic type like this though. Please refer to the following blog post for more information about this.

Generic type parameters and dynamic types in C#: https://blog.magnusmontin.net/2014/10/31/generic-type-parameters-and-dynamic-types-in-csharp/

mm8
  • 163,881
  • 10
  • 57
  • 88