#742 – A Simple Example of Inheritance

Here’s a simple example of inheritance in C#.

The Dog class has a Name property and a Bark method.

    public class Dog
    {
        public string Name { get; set; }

        public void Bark()
        {
            Console.WriteLine(Name + " : Woof");
        }
    }

The Terrier class inherits from Dog and adds a HuntVermin method.

    public class Terrier : Dog
    {
        public void HuntVermin()
        {
            Console.WriteLine(Name + " off to find vermin");
        }
    }

An object of type Dog has access to the Name property and the Bark method.  An object of type Terrier also has access to Name and Bark and also to the HuntVermin method.

            Dog d = new Dog();
            d.Name = "Kirby";
            d.Bark();

            Terrier t = new Terrier();
            t.Name = "Jack";
            t.Bark();
            t.HuntVermin();

742-001

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.

One Response to #742 – A Simple Example of Inheritance

  1. Zach says:

    not sure if I would use a different name for the terrier… Heh…

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: