+ 2
polymorphism in c# ???
i have a question about polymorphism in c# if we have this two class : class animal { // field and methods } class dog : animal { } what is the difference between this two line of code : animal a = new dog(); dog a = new dog(); When and why we use each of them ? and what is mean ?
3 Respostas
+ 6
Theres alot more to this but to keep it simple the parent variable can hold a object refrenece of any of is sub classes and by doing this it's important that you agree to treat this object as if it was the type your using to refer to the object.
If you understand that then all you need to know is that any overridden methods or hidden variables will be called instead on the type of object and not by the the type that is referring to the object...
+ 1
Have a look at this thread.
https://www.sololearn.com/Discuss/1957/what-s-the-difference-a-animal-dog-new-dog-b-dog-dog-new-dog
https://code.sololearn.com/cEmEMnM14RCs
Although GetType says it is a dog, because it was created as one.
animal dog is not able to use the method sniffbum because the type at the moment of declaration it is an animal.
0
thank you :)