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?
You can create custom dynamic objects by using the classes in the System. Dynamic namespace. For example, you can create an ExpandoObject and specify the members of that object at run time. You can also create your own type that inherits the DynamicObject class.
You can do dynamic casting by calling a method which takes a parameter of the type you want to change your current type to. Take this for example: public class Example{ Example e1=new Example(); private Object obj=new Object(); e1.
In C++, dynamic casting is mainly used for safe downcasting at run time. To work on dynamic_cast there must be one virtual function in the base class. A dynamic_cast works only polymorphic base class because it uses this information to decide safe downcasting.
The primary purpose for the dynamic_cast operator is to perform type-safe downcasts. A downcast is the conversion of a pointer or reference to a class A to a pointer or reference to a class B , where class A is a base class of B .
Three options:
private dynamic obj;
and it will compile and find the right method at execution timeBasically 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With