#346 – Polymorphism

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
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

5 Responses to #346 – Polymorphism

  1. Pingback: #445 – Differences Between an Interface and an Abstract Class « 2,000 Things You Should Know About C#

  2. Pingback: #675 – Polymorphic Behavior Requires virtual / override Combination « 2,000 Things You Should Know About C#

  3. Pingback: #676 – An Overridden Method Can Itself Be Overridden « 2,000 Things You Should Know About C#

  4. Pingback: #677 – Method Marked with new Modifier Cannot Be Overridden « 2,000 Things You Should Know About C#

  5. Pingback: #683 – Two Ways an Object Can Behave Polymorphically « 2,000 Things You Should Know About C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: