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); } }
Categories: Uncategorized
Comments (0)
Trackbacks (0)
Leave a comment
Trackback