#334 – A Base Class Variable Can Refer to Instances of Derived Classes

A variable whose type is a particular class can refer to instances of that class or it can refer to instances of any derived classes.

Assume that we have a Dog class (base class) and a Terrier class (derived class) that inherits from Dog.  A variable of type Dog can then refer to either a Dog or a Terrier.

Dog kirby = new Dog("Kirby", 15);

// Dog variable can point to Terrier
Dog jack = new Terrier("Jack", 17, "Surly");

// Terrier variable can also point to Terrier
Terrier bubba = new Terrier("Bubba", 2, "Happy");

Notice that even though the variable jack is of type Dog, it still points to an instance of a Terrier.

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.

3 Responses to #334 – A Base Class Variable Can Refer to Instances of Derived Classes

  1. Pingback: #335 – Accessing a Derived Class Using a Base Class Variable « 2,000 Things You Should Know About C#

  2. Lei Yu says:

    Hi, Sean. I’m a C# learner from China, and I love your C# posts very much. I want to know whether I can translate your posts into Chinese in my blogs? Certainly, I’ll give the links of your original posts. Waiting for your Reply! Lei Yu

    • Sean says:

      Hello Lei,

      I’m okay with your translating them and reposting, as long as you clearly mention me as the author and include a link back to my blog.

      Sean

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: