User1551892
User1551892

Reputation: 3384

Does base class object holds the drived class object?

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.

Upvotes: 1

Views: 95

Answers (3)

tomkuj
tomkuj

Reputation: 81

You could even do

(bobject as Derived2).Method1(string);

This is because the resolution is based on the variable type.

Upvotes: 0

Dennis
Dennis

Reputation: 37780

what exactly happens when we assign derived class object to base abstract class object

There's no object assignment in you code, there's variable assignment. After assignment, variable bobject refers to the same object, as d2 does. Object type (and anything in the object state) remains unchanged.

Now I want to access the Dervied2 class method Method1 which accept string argument

You can't do this in your sample without casting bobject to Derived2:

((Derived2)bobject).Method1(str)

I want to keep things generic

Then, you shouldn't try to access members, which are not the part of base class.

Upvotes: 1

Darren
Darren

Reputation: 70776

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");

Upvotes: 0

Related Questions