Reputation: 119
this might be a easy question but I am struggling with it.
I have two classes that are derived from a base class
class Base
{
public int BaseProperty;
...
}
class A: Base
{
public int Property_derived;
...
}
Class B: Base
{
public int Property_derived;
...
}
Now I have a UI form, that got a textbox that should display the property of derived class(I assure the number and datatypes of properties of all derived classes would be same) I have done something like:
textbox1.text = objectA.Property_derived;
how do I change it to make it more generic like:
textbox1.text = objecttypedoesntmatter.Property_derived;
so that I should be able to use the same user interface for any derived class. Any help much appreciated. Many Thanks
Upvotes: 0
Views: 78
Reputation: 14700
What you need to do is define your Property_derived in the base class, and thus have it as part of the shared contract of all derived classes. Polymorphism, a property of inheritance, will call the derived, overridden property. Note, though, that this will work for a property, not a field:
class Base
{
public virtual int MyProperty {get { return 1;} }
}
class A: Base
{
public override int MyProperty { get { return 5; } }
}
class B: Base
{
public override int MyProperty { get { retun 7; } }
}
Upvotes: 5