1

There is a behavior in C# I really do not understand:

class Animal {
        public string species = "animal";

        public void Introduce() {
            Console.WriteLine(species);
        }
    }


    class Cat: Animal {
        new public string species = "cat";

        // public void Introduce() {Console.WriteLine(species);}
    }

    class Program
    {
        static void Main(string[] args)
        {
            var cat = new Cat();
            cat.Introduce();
        }
    }

This piece of code, when executed, outputs >>> animal.
For me, since Cat inherits Animal, calling cat.Introduce should call Animal.Introduce "in the scope of the cat instance". ie I don't understand why the program picks the species field of Animal and not the one of Cat...

I know I could use workarounds, but I believe I'm missing some point about c# design, can someone explain this behavior?

Thanks

SPH
  • 478
  • 2
  • 6

1 Answers1

10

I don't understand why the program picks the species field of Animal and not the one of Cat...

Because the new modifier hides the inherited species member... but only inside the Cat instance. You call the method on the base class, which only knows its own species member.

If you give your Cat class an IntroduceCat() method where you print its species and you call it, you'll see the "cat" string being printed.

If you want to override the member in a derived class, you must mark the member as virtual in the base class and override it in the derived class. But you can't do that to fields, so you'll have to make it a property.

But you probably just want to assign a different value, and you can do so in your constructor.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272