views:

80

answers:

2

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?

+8  A: 

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()
    {
    }
}
dtb
A: 

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
  }
}
Tom Anderson
you guys type too fast!
Tom Anderson
They may have Visual Studio open already and bang out these with AutoCompletion =)
Mike Atlas
i guess, or they only post half the answer, then come back and make it pretty later.
Tom Anderson
Thanks guys, I really appreciate the help and examples. =) and yeah Intellisense on here would be awesome.
Matt