DOES BASE CLASS OBJECT HOLD THE DERIVED CLASS OBJECT?

Chintoo Semi

Total Post:135

Points:947
Posted by  Chintoo Semi
C#
 819  View(s)
Ratings:
Rate this:

Below is the code and I want to understand few things:

public class Test {

    public void dosomething( ) {

      Derived2 d2 = new Derived2 () ;

      Base bobject = d2;

      string str = "str" ;

      bobject.Method1( str ); // I want to call Method1 of Derived1 class

    }

  }

  public class Derived2 : Derived1 {

    public void Method1( string s ) {

    }

  }

  public class Derived1 : Base {

    public override void Method1( double d ) {

    }

    public override void Method2( double d ) {

    }

  }

  public abstract class Base {

    public abstract void Method1( double d );

    public abstract void Method2( double d );

  }

I would like to know, what exactly happens when we assign derived class object to base abstract class object. I know instantiating abstract class is not possible. In my case, I am deriving class Derived1 and assigning object of Derived2 class to base abstract class object. Now I want to access the Dervied2 class method Method1 which accept string argument. Somehow, I am unable to access this method. There are multiple classes exist which are derived from base abstract class. I want to keep things generic.

  1. Pravesh Singh

    Post:412

    Points:2888
    Re: Does base class object hold the derived class object?

    Hi Chintoo,

    bobject is a type of Base which has two methods which accept a double, not a string (That method is defined in Derived2's implementation).

    To do what you requrie you'd need to cast bobject to Derived2, like:

    var d3 = bobject as Derived2;

    d3.Method1("String");

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!