Dynamic Casting in C#

Dynamic Casting? Well… almost. In fact, we are dynamically converting and not casting. The problem that remains is that the resultant object does doesn’t “know” at design time what it is capable of (a.k.a. not aware of the methods it has). However, this should not be a problem if there is an interface that is common to the superset of things we want to cast to.

To state an example, let us say there is an interface and 3 classes as below.

Now, we can try accessing these objects through converting at runtime. Note that the examples here might look trivial, but the application for this is when you know the type of the object only at runtime.

The output to this is as below.

DummyA has spit out the property from base as it was not overridden. However, as evident from the type reflected, the objects does get converted to desired types in each case. Also, note that the base property is declared as virtual so that it could be overridden.

In this particular case above, we already had the object and wanted them to be converted to a desired type. That scenario is different from (say), if we do not have an object and want to instantiate based on runtime information. Below is how we can do that.

Output is exactly the same as in the previous case. The difference here is that we “created” the instance in this case whereas “got” the instance in the previous one.

1 thought on “Dynamic Casting in C#

Leave a Reply

Your email address will not be published. Required fields are marked *