How can I cast object dynamically?
c#, casting
Solution
Three options:
- If you control both classes, and you can make them implement a common interface that includes everything you need, then do that - and cast to the interface
- If you're using C# 4 and .NET 4, you can use dynamic typing - just declare the variable as `private dynamic obj;` and it will compile and find the right method at execution time
- Otherwise, use reflection to find and call the method.
Basically casting based on an execution time type doesn't make sense, as part of the point of casting is to give the compiler more information... and you simply don't have that in this case.
The first option is by far the nicest if you can possibly achieve it.
Problem
I am pretty sure this was asked before but unfortunately the only thing I've found was this that was not solution for me. In my current project I do something like: ``` private object obj; private void Initialize() { obj.Initialize(); } private void CreateInstanceA() { obj = Activator.CreateInstance(typeof(MyClassA)); } private void CreateInstanceB() { obj = Activator.CreateInstance(typeof(MyClassB)); } ``` This code does not work of course because I've not cast `obj` because its type changes dynamically. How can I cast it dynamically?