#346 – Polymorphism
June 15, 2011 5 Comments
Recall that polymorphism is one of the three core principles of object-oriented programming.
Polymorphism is the idea that the same code can act differently, depending on the underlying type of the object being acted upon. The type of the object is determined at run-time, rather than at compile-time.
In C#, you can use a variable declared as a base type to refer to instances of one or more derived types. Polymorphism allows you to call a method that exists in the base type but whose implementation exists in the derived types. The appropriate method in the derived type will be called, based on the type of the object.
Dog d; d = new Terrier("Jack", 15); d.Bark(); // Terrier.Bark is called d = new Shepherd("Kirby", 12); d.Bark(); // Shepherd.Bark is called
Pingback: #445 – Differences Between an Interface and an Abstract Class « 2,000 Things You Should Know About C#
Pingback: #675 – Polymorphic Behavior Requires virtual / override Combination « 2,000 Things You Should Know About C#
Pingback: #676 – An Overridden Method Can Itself Be Overridden « 2,000 Things You Should Know About C#
Pingback: #677 – Method Marked with new Modifier Cannot Be Overridden « 2,000 Things You Should Know About C#
Pingback: #683 – Two Ways an Object Can Behave Polymorphically « 2,000 Things You Should Know About C#