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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

//Interface

publicinterfaceIDummy

{

stringEcho{get;}

}

//Base Class, implemented from interface

publicclassDummyBase:IDummy

{

publicvirtualstringEcho{get{return"Dummy Base";}}

}

//Inherited class, without an override on property

publicclassDummyA:DummyBase

{

publicstringEcho{get{return"Dummy A";}}

}

//Inherited class, with an override on property

publicclassDummyB:DummyBase

{

publicoverridestringEcho{get{return"Dummy B";}}

}

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.

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.