tags:

views:

183

answers:

2

I don't understand why my output is not how I think it should be. I think that it should be Dog barks line break Cat meows. But there is nothing there.

Code:

namespace ConsoleApplication2
{
  class Program
  {
    static void Main(string[] args)
    {
      Pets pet1 = new Dog();
      Pets pet2 = new Cat();
      pet1.Say();
      pet2.Say();
      Console.ReadKey();
    }
  }

  class Pets
  {
   public void Say() { }
  }

  class Dog : Pets
  {
   new public void Say() { Console.WriteLine("Dog barks."); }
  }

  class Cat : Pets 
  {
   new public void Say() { Console.WriteLine("Cat meows."); }
  }
}

I have tried to go through the c# programming guide on MSDN but I find it very difficult to understand some of the examples on there. If someone could link to a good "inheritance for dummies" site, it would be much appreciated.

+18  A: 

Make the Say function in your base class virtual and then override this function in your derived classes:

namespace ConsoleApplication2
{
  class Program
  {
    static void Main(string[] args)
    {
      Pets pet1 = new Dog();
      Pets pet2 = new Cat();
      pet1.Say();
      pet2.Say();
      Console.ReadKey();
    }
  }

  class Pets
  {
   public virtual void Say() {
      Console.WriteLine("Pet makes generic noise");
 }
  }

  class Dog : Pets
  {
    public override void Say() { Console.WriteLine("Dog barks."); }
  }

  class Cat : Pets 
  {
    public override void Say() { Console.WriteLine("Cat meows."); }
  }
}
fletcher
+13  A: 

The new modifier as you've written it:

class Dog : Pets
{
 new public void Say() { Console.WriteLine("Dog barks."); }
}

essentially means that the Say method you've defined is only called when that instance is used as an instance of Dog.

So

Dog dog = new Dog();
dog.Say(); // barks (calls Dog.Say)
Pet pet = dog;
pet.Say(); // nothing (calls Pet.Say)

That explains why you received the results you have; for what you wanted, use virtual methods -- @fletcher's answer explains it well.

Mark Rushakoff
+1 I never even knew you could use the new keyword in this way, wierd.
Jimmy Hoffa