Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I cast object dynamically?

Tags:

c#

casting

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?

like image 997
Leri Avatar asked May 31 '12 14:05

Leri


People also ask

How do you make an object dynamic?

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.

How do you cast dynamic type in Java?

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.

When use dynamic cast?

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.

Why do we use dynamic_ cast in c++?

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 .


1 Answers

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.

like image 156
Jon Skeet Avatar answered Oct 04 '22 11:10

Jon Skeet