Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling child class method from base class C#

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";
    }
}
like image 763
Tisha Anand Avatar asked Jan 05 '23 22:01

Tisha Anand


1 Answers

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"; 
like image 97
Dmitry Bychenko Avatar answered Jan 15 '23 18:01

Dmitry Bychenko