Matt
Matt

Reputation: 33

Trouble with inheritance

I'm relatively new to programming so excuse me if I get some terms wrong (I've learned the concepts, I just haven't actually used most of them).

Trouble: I currently have a class I'll call Bob its parent class is Cody, Cody has method call Foo(). I want Bob to have the Foo() method as well, except with a few extra lines of code. I've attempted to do Foo() : base(), however that doesn't seem to work like. Is there some simple solution to this?

Upvotes: 3

Views: 115

Answers (3)

Henk Holterman
Henk Holterman

Reputation: 273179

The standard form (without polymorphism) is:

class Cody
{
    public void Foo () 
    {
    }
}

class Bob : Cody
{
    public new void Foo()
    {
        base.Foo(); // Cody.Foo()
        // extra stuff
    }
}

If you want polymorphism, the following 2 lines change:

// Cody
 public virtual void Foo () 

// Bob 
public override void Foo()

The difference shows when calling on a Bob instance through a Cody reference:

Bob b = new Bob();
Cody c = b;

b.Foo();    // always Bob.Foo()
c.Foo();    // when virtual, Bob.Foo(), else Cody.Foo()

Upvotes: 2

dtb
dtb

Reputation: 217253

You can override Foo in the derived class and call the overridden base class implementation using base.Foo():

class Cody
{
    public virtual void Foo()
    {
        Console.WriteLine("Cody says: Hello World!");
    }
}

class Bob : Cody
{
    public override void Foo()
    {
        base.Foo();
        Console.WriteLine("Bob says: Hello World!");
        base.Foo();
    }
}

Output of new Bob().Foo():

Cody says: Hello World!
Bob says: Hello World!
Cody says: Hello World!

Constructors use a slightly different syntax to call the constructor in a base class, because they have the requirement that the base class constructor must be called before the constructor in the derived class:

class Cody
{
    public Cody()
    {
    }
}

class Bob : Cody
{
    public Bob() : base()
    {
    }
}

Upvotes: 8

Tom Anderson
Tom Anderson

Reputation: 10827

You need to mark the base method as virtual, override it in the inherited class, and then call the base that way. You can either call the base before or after your code in the "Cody" class it is up to you on calling order.

class Bob
{
  public virtual void Foo()
  {

  }
}

class Cody
{
  public override void Foo()
  {
    base.Foo()
    // your code
  }
}

Upvotes: 0

Related Questions