Click here to Skip to main content
11,634,568 members (62,775 online)
Click here to Skip to main content

Introduction to inheritance, polymorphism in C#

, 9 Oct 2001 CPOL 776.7K 4.1K 174
Rate this:
Please Sign up or sign in to vote.
An elementary introduction to inheritance, polymorphism in C# using simple code snippets
<link rel="stylesheet" type=text/css href="d:\nish\cp\global.css">

Introduction

This little article is intended for rank .NET newbies who are making their first attempts at C# programming. I assume that they have done some elementary C++ programming and know what classes and member functions are. Using a few simple code snippets we'll see how C# supports inheritance and polymorphism.

Inheritance & Polymorphism

When you derive a class from a base class, the derived class will inherit all members of the base class except constructors, though whether the derived class would be able to access those members would depend upon the accessibility of those members in the base class. C# gives us polymorphism through inheritance. Inheritance-based polymorphism allows us to define methods in a base class and override them with derived class implementations. Thus if you have a base class object that might be holding one of several derived class objects, polymorphism when properly used allows you to call a method that will work differently according to the type of derived class the object belongs to.

Consider the following class which we'll use as a base class.

class Animal
{
    public Animal()
    {
        Console.WriteLine("Animal constructor");
    }
    public void Greet()
    {
        Console.WriteLine("Animal says Hello");
    }
    public void Talk()
    {
        Console.WriteLine("Animal talk");
    }
    public virtual void Sing()
    {
        Console.WriteLine("Animal song");
    }
};

Now see how we derive another class from this base class.

class Dog : Animal
{
    public Dog()
    {
        Console.WriteLine("Dog constructor");
    }
    public new void Talk()
    {
        Console.WriteLine("Dog talk");
    }
    public override void Sing()
    {
        Console.WriteLine("Dog song");
    }
};

Now try this code out.

Animal a1 = new Animal();
a1.Talk();
a1.Sing();
a1.Greet();

//Output
Animal constructor
Animal talk
Animal song
Animal says Hello

Okay, that came out just as expected. Now try this code out.

Animal a2 = new Dog();
a2.Talk();
a2.Sing();
a2.Greet();

//Output
Animal constructor
Dog constructor
Animal talk
Dog song
Animal says Hello

We have an object of type Animal, but it references an object of type Dog. Thus you can see the base class constructor getting called first followed by the derived class constructor. Now we call Talk() and find that the method that's executed is the base class method. That's not surprising when you consider that the object was declared to be of the base type which in our case is Animal. Now when we call Sing(), we find that the derived class method has got called. This is because in the base class the method is prototyped as public virtual void Sing() and in the derived class we have overridden it by using public override void Sing(). In C#, we need to explicitly use the override keyword as opposed to C++ where we didn't have to do that. And finally when we call Greet() the base class method gets called and this is not confusing at all specially since the derived class has not even implemented the method.

Now try the following code out.

Dog d1 = new Dog();
d1.Talk();
d1.Sing();
d1.Greet();

//Output
Animal constructor
Dog constructor
Dog talk
Dog song
Animal says Hello

Okay, here everything came out as expected. No rude surprises there. The fact that we could invoke the Greet() method is proof of inheritance in C#, not that anyone had any doubts to begin with I guess. Now take a look at this new class we'll be using as a base class for some other classes.

class Color
{
    public virtual void Fill()
    {
        Console.WriteLine("Fill me up with color");
    }
    public void Fill(string s)
    {
        Console.WriteLine("Fill me up with {0}",s);
    }
};

Now run this code out.

Color c1 = new Color();
c1.Fill();
c1.Fill("red");

//Output
Fill me up with color
Fill me up with red

Okay, that went fine, I'd say. Now let's derive a class from this class.

class Green : Color
{
    public override void Fill()
    {
        Console.WriteLine("Fill me up with green");
    }
};

Now let's try this code out.

Green g1 = new Green();
g1.Fill();
g1.Fill("violet");

//Output
Fill me up with green
Fill me up with violet

Well, that went fine too. Thus if you have overloaded methods, you can mark some of them as virtual and override them in the derived class. It's not required that you have to override all the overloads. Now I want to demonstrate some stuff on overloaded constructors. For that we'll use the following base class.

class Software
{
    public Software()
    {
        m_x = 100;
    }
    public Software(int y)
    {
        m_x = y;
    }
    protected int m_x;
};

Now we'll derive a class from the above class.

class MicrosoftSoftware : Software
{
    public MicrosoftSoftware()
    {
        Console.WriteLine(m_x);
    }
};

Now try this code out

MicrosoftSoftware m1 = new MicrosoftSoftware();
//MicrosoftSoftware m2 = new MicrosoftSoftware(300); //won't compile

//Output
100

The base class had two overloaded constructors. One that took zero arguments and one that took an int. In the derived class we only have the zero argument constructor. Constructors are not inherited by derived classes. Thus we cannot instantiate a derived class object using the constructor that takes an int as parameter. As you will deduce from the output we got, the base class constructor that called was the default parameter-less constructor. Now take a look at this second derived class.

class DundasSoftware : Software
{
    //Here I am telling the compiler which
    //overload of the base constructor to call
    public DundasSoftware(int y) : base(y)
    {
        Console.WriteLine(m_x);
    }
    
    //Here we are telling the compiler to first
    //call the other overload of the constructor
    public DundasSoftware(string s, int f) : this(f)
    {
        Console.WriteLine(s);
    }
};

Here we have two constructors, one that takes an int and one that takes a string and an int. Now lets try some code out.

DundasSoftware du1 = new DundasSoftware(50);

//Output
50

DundasSoftware du2 = new DundasSoftware("test",75);

//Output
75
test

There, now that you've seen how it came out, things are a lot clearer I bet. You can use the this and base access keywords on other methods too, and not just on constructors.

Conclusion

This article does not discuss interfaces. At least not in it's current version. I'll probably add the usage of interfaces in the next update. But for now, I recommend that you read up on interfaces from elsewhere.

History

  • 09 Jul 2002 - Article redone completely, sample project added.
  • 10 Oct 2001 - Article posted [My first article on CP]

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Nish Nishant
United States United States
Nish Nishant is a Software Architect/Consultant based out of Columbus, Ohio. He has over 15 years of software industry experience in various roles including Lead Software Architect, Principal Software Engineer, and Product Manager. Nish is a recipient of the annual Microsoft Visual C++ MVP Award since 2002 (13 consecutive awards as of 2014).

Nish is an industry acknowledged expert in the Microsoft technology stack. He authored
C++/CLI in Action for Manning Publications in 2005, and had previously co-authored
Extending MFC Applications with the .NET Framework for Addison Wesley in 2003. In addition, he has over 140 published technology articles on CodeProject.com and another 250+ blog articles on his
WordPress blog. Nish is vastly experienced in team management, mentoring teams, and directing all stages of software development.

Contact Nish : You can reach Nish on his google email id voidnish.

Website and Blog

You may also be interested in...

Comments and Discussions

 
GeneralMy vote of 5 Pin
majid torfi28-Oct-14 2:20
membermajid torfi28-Oct-14 2:20 
GeneralMy vote of 4 Pin
Member 989351512-Sep-13 22:58
memberMember 989351512-Sep-13 22:58 
QuestionThanks Pin
hiral kahar14-Jul-13 6:00
memberhiral kahar14-Jul-13 6:00 
GeneralMy vote of 4 Pin
Mohammed Hameed9-May-13 19:44
professionalMohammed Hameed9-May-13 19:44 
Questioni have following question about inheritance Pin
Member 91131727-Feb-13 4:10
memberMember 91131727-Feb-13 4:10 
Questionc sharp programming Pin
misbahafridi26-Nov-12 7:39
membermisbahafridi26-Nov-12 7:39 
GeneralMy vote of 4 Pin
nilesh.nildata31-Oct-12 0:07
membernilesh.nildata31-Oct-12 0:07 
GeneralMy vote of 5 Pin
RevaOnwards29-Oct-12 9:54
memberRevaOnwards29-Oct-12 9:54 
GeneralMy vote of 4 Pin
shak imran20-Sep-12 20:34
membershak imran20-Sep-12 20:34 
QuestionInheritance and polymorphism in C # Pin
Jyoti516-Sep-12 13:14
memberJyoti516-Sep-12 13:14 
AnswerRe: Inheritance and polymorphism in C # Pin
jagadesh43725-Mar-13 19:41
memberjagadesh43725-Mar-13 19:41 
GeneralMy vote of 3 Pin
usrikanthvarma13-Aug-12 2:43
memberusrikanthvarma13-Aug-12 2:43 
GeneralMy vote of 3 Pin
hareesh.devunoori3-Aug-12 4:34
memberhareesh.devunoori3-Aug-12 4:34 
GeneralMy vote of 4 Pin
Apoorva Keshav12-Jul-12 17:55
memberApoorva Keshav12-Jul-12 17:55 
GeneralMy vote of 5 Pin
Tapan dubey11-Jun-12 3:16
memberTapan dubey11-Jun-12 3:16 
GeneralMy vote of 3 Pin
sankarrbs8-May-12 20:18
membersankarrbs8-May-12 20:18 
GeneralMy vote of 5 Pin
Tarun K.S7-Jul-11 4:48
memberTarun K.S7-Jul-11 4:48 
GeneralMy vote of 5 Pin
kdchandima12-May-11 4:17
memberkdchandima12-May-11 4:17 
GeneralVery Nice Article Pin
govind_ind12318-Apr-11 19:35
membergovind_ind12318-Apr-11 19:35 
QuestionDoubt abt new keyword Pin
Srigurusankar27-Feb-11 19:33
memberSrigurusankar27-Feb-11 19:33 
AnswerRe: Doubt abt new keyword Pin
TweakBird25-May-11 0:55
memberTweakBird25-May-11 0:55 
GeneralMy vote of 3 Pin
SunnyBuzz28-Jul-10 22:30
memberSunnyBuzz28-Jul-10 22:30 
QuestionIs it possible to do polymorphism with out inheritnace???? Pin
amistry_petlad10-Jun-10 3:55
memberamistry_petlad10-Jun-10 3:55 
GeneralUnable to cast object of type 'Inheritance.person' to type 'Inheritance.employee'. Pin
anup choudhari30-May-10 23:46
groupanup choudhari30-May-10 23:46 
General... Pin
69er6-Feb-10 0:02
member69er6-Feb-10 0:02 
GeneralGREAT Pin
shanto01327-Aug-09 17:42
membershanto01327-Aug-09 17:42 
GeneralNice Artical Pin
rk4dotnet1-Apr-09 1:32
memberrk4dotnet1-Apr-09 1:32 
Question.net Pin
sandik484-Jan-09 19:44
membersandik484-Jan-09 19:44 
AnswerRe: .net Pin
Nishant Sivakumar5-Jan-09 1:58
mvpNishant Sivakumar5-Jan-09 1:58 
sandik48 wrote:
i how connect to link b/w the sql and asp insert command


Please ask this question in the ASP.NET forum. It really has nothing to do with this article.


GeneralIt has all about Inheritance Pin
Shiv...26-Aug-07 23:39
memberShiv...26-Aug-07 23:39 
Generalmade easy to undertand Pin
pallavipatil0121-Jun-07 20:52
memberpallavipatil0121-Jun-07 20:52 
GeneralOutput seems to have an error Pin
ComputerKat19-Jan-07 8:34
memberComputerKat19-Jan-07 8:34 
GeneralRe: Output seems to have an error Pin
peter200210-Mar-07 11:49
memberpeter200210-Mar-07 11:49 
Generalquestion about last example Pin
daddion30-Oct-06 16:52
memberdaddion30-Oct-06 16:52 
GeneralRe: question about last example Pin
tbenda11-Dec-06 6:23
membertbenda11-Dec-06 6:23 
Questionwhy the new modifier? Pin
logistum29-Jul-06 11:22
memberlogistum29-Jul-06 11:22 
AnswerRe: why the new modifier? Pin
beren77722-Aug-06 23:29
memberberen77722-Aug-06 23:29 
GeneralGood tutorial; one question Pin
Huline31-Oct-05 7:38
memberHuline31-Oct-05 7:38 
GeneralRe: Good tutorial; one question Pin
sikemullivan21-Dec-05 9:29
membersikemullivan21-Dec-05 9:29 
Generalexcellent Pin
hollyireland28-Oct-04 10:56
memberhollyireland28-Oct-04 10:56 
GeneralRe: excellent Pin
Nishant S28-Oct-04 16:11
staffNishant S28-Oct-04 16:11 
GeneralIt helped! Thankx Pin
Kavya Menon18-Sep-03 2:30
memberKavya Menon18-Sep-03 2:30 
GeneralRe: It helped! Thankx Pin
Nishant S18-Sep-03 3:49
editorNishant S18-Sep-03 3:49 
GeneralNice beginners article Nish Pin
Brian Delahunty28-Dec-02 8:06
memberBrian Delahunty28-Dec-02 8:06 
GeneralRe: Nice beginners article Nish Pin
leppie28-Dec-02 8:50
memberleppie28-Dec-02 8:50 
GeneralRe: Nice beginners article Nish Pin
Nishant S28-Dec-02 19:32
editorNishant S28-Dec-02 19:32 
GeneralRe: Nice beginners article Nish Pin
Brian Delahunty8-Jan-03 1:46
memberBrian Delahunty8-Jan-03 1:46 
GeneralRe: Nice beginners article Nish Pin
Nishant S28-Dec-02 19:31
editorNishant S28-Dec-02 19:31 
GeneralRe: Nice beginners article Nish Pin
Brian Delahunty8-Jan-03 1:44
memberBrian Delahunty8-Jan-03 1:44 
GeneralRe: Nice beginners article Nish Pin
Anonymous26-May-04 2:48
sussAnonymous26-May-04 2:48 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150728.1 | Last Updated 10 Oct 2001
Article Copyright 2001 by Nish Nishant
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid