0

new to C#.

I have a strange problem, as I am learning C# now, the following code is supposed to output the same value:

public class Animal {
    public void sound() {
        Console.WriteLine("...");
    }
}

public class Dog : Animal {
    public void sound() {
        Console.WriteLine("Woof");
    }
}

public class Cat : Animal {
    public void sound() {
        Console.WriteLine("Meaw"); 
    }
}

// in Main(){}; 

Animal animal = new Animal();
Dog dog = new Dog();
Cat cat = new Cat();

animal.sound();
dog.sound();
cat.sound();

From what I have learned the value for all three methods should be the same, as in: ... but I get the following:

...
Woof
Meaw

How can this be possible without using the virtual and override properties?

elektra
  • 55
  • 2
  • 19
  • This question is not a duplicate – elektra Sep 07 '22 at 08:24
  • It is.......... –  Sep 07 '22 at 08:25
  • Actually it isn't, have you read the my question, it seems like a bug @MySkullCaveIsADarkPlace – elektra Sep 07 '22 at 08:26
  • No, it's not a bug. And it is a duplicate, despite your insistence it's not... You have to read the question and answers (most importantly the answers) that is linked as duplicate. –  Sep 07 '22 at 08:26
  • 1
    The output is defenitvely correct... it should be `...` for all three objects in case of `Animal dog = new Dog(); Animal cat = new Cat();`. Maybe you have to go back to the basis of polymorphism – Marco Beninca Sep 07 '22 at 08:56
  • 2
    Change the code to `Animal dog = new Dog();` and `Animal cat = new Cat();` then run it again. All the outputs will be "...". Then decorate base method as `virtual` and the derived methods as `override` and run it again. The outputs will now change to "...", "Wood", "Meaw". – Matthew Watson Sep 07 '22 at 09:00
  • @MarcoBeninca The output is incorrect, because if you read my question I am expecting `...` but that's not what I am getting. Instead I get three different values. – elektra Sep 07 '22 at 09:24
  • @MatthewWatson I already get `"...", "Woof", "Meaw".` and I am saying this is wrong, because the output should be `...` because I am not using `virtual` or `override` keywords here – elektra Sep 07 '22 at 09:25
  • 1
    @Displayname the output is correct because you instantiated `Dog` and `Cat` using `Dog` and `Cat` references... please try to understand you are wrong and the compiler is doing absolutely the rigth thing – Marco Beninca Sep 07 '22 at 09:51
  • 2
    @MarcoBeninca Thanks, I just understood now, I was using this tutorial https://www.w3schools.com/cs/cs_polymorphism.php (see 2nd Example) and wandered why I wasn't getting the same result until you pointed it out. Thanks a lot and sorry for the frustrations everyone – elektra Sep 07 '22 at 10:01

0 Answers0