Home > Uncategorized > Downcasting using Reflection C#

Downcasting using Reflection C#

You cannot cast an object to a derived type in C#, this is called downcasting.

I.e.

class MyBase {}
class MyDerived : MyBase {}

MyBase SomeBase = new MyBase();
MyDerived SomeDerived = (MyDerived)SomeBase;

Will fail, as will

MyDerived SomeDerived = SomeBase as MyDerived

– Which will set SomeDerived to Null.

A way around this is to use reflection:

    public MyDerived(MyBase baseClass)
    {
        foreach (PropertyInfo piBase in typeof(MyBase).GetProperties())
        {
            PropertyInfo piThis = GetType().GetProperty(piBase.Name);
            piThis.SetValue(this, piBase.GetValue(baseClass, null), null);
        }
    }
Advertisements
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: