Is it possible to call child class method from base class reference? Please suggest...
Code example is given below:
public class Parent
{
public string Property1 { get; set; }
}
public class Child1:Parent
{
public string Child1Property { get; set; }
}
public class Child2 : Parent
{
public string Child2Property { get; set; }
}
public class Program
{
public void callMe()
{
Parent p1 = new Child1();
Parent p2 = new Child2();
//here p1 & p2 have access to only base class member.
//Is it possible to call child class memeber from the base class reference based on the child class object it is referring to?
//for example...is it possible to call as below:
//p1.Child1Property = "hi";
//p2.Child1Property = "hello";
}
}
Actually you´ve created a Child1
and Child2
instances, so you can cast to them:
Parent p1 = new Child1();
Parent p2 = new Child2();
// or ((Child1) p1).Child1Property = "hi";
(p1 as Child1).Child1Property = "hi";
(p2 as Child2).Child2Property = "hello";
To check if cast successful, test for null
:
Child1 c1 = p1 as Child1;
if (c1 != null)
c1.Child1Property = "hi";
A better design, however, is assign to Child1
and Child2
local variables
Child1 p1 = Child1();
p1.Child1Property = "hi";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With