Click here to Skip to main content
Click here to Skip to main content

Introduction to inheritance, polymorphism in C#

By , 9 Oct 2001
 

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)

About the Author

Nish Sivakumar
United States United States
Member
Nish is a real nice guy who has been writing code since 1990 when he first got his hands on an 8088 with 640 KB RAM. Originally from sunny Trivandrum in India, he has been living in various places over the past few years and often thinks it’s time he settled down somewhere.
 
Nish has been a Microsoft Visual C++ MVP since October, 2002 - awfully nice of Microsoft, he thinks. He maintains an MVP tips and tricks web site - www.voidnish.com where you can find a consolidated list of his articles, writings and ideas on VC++, MFC, .NET and C++/CLI. Oh, and you might want to check out his blog on C++/CLI, MFC, .NET and a lot of other stuff - blog.voidnish.com.
 
Nish loves reading Science Fiction, P G Wodehouse and Agatha Christie, and also fancies himself to be a decent writer of sorts. He has authored a romantic comedy Summer Love and Some more Cricket as well as a programming book – Extending MFC applications with the .NET Framework.
 
Nish's latest book C++/CLI in Action published by Manning Publications is now available for purchase. You can read more about the book on his blog.
 
Despite his wife's attempts to get him into cooking, his best effort so far has been a badly done omelette. Some day, he hopes to be a good cook, and to cook a tasty dinner for his wife.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 4professionalMohammed Hameed9 May '13 - 19:44 
Very nice explanation, useful for freshers.
Questioni have following question about inheritancememberMember 91131727 Feb '13 - 4:10 
public class Animal
{
public Animal()
{
}
public string dance(object obj)
{
return obj.ToString()+" Dance on floor.";
}
public string Walk(object obj)
{
return obj.ToString() + " Walk on floor. ";
}
public string sing(object obj)
{
return obj.ToString() + " Sing on floor. ";
}
}
 
public class Dog:Animal
{
public void dog(){}
public string Run(object obj)
{
return obj.ToString() + "is Runing.";
}
public string Bark(object obj)
{
return obj.ToString() + "is Barking.";
}
}
 
------ in main method i do the following ------
Animal ani = new Animal();
Dog dogi = new Dog();// i am able to access all the methods in animal and dog
Animal ann = dogi;// here i am able to access only animal methods not dog methods why like "ann.Run();" ?
string abc = ann.dance(ann).ToString();
 
my question is like this when i create dog object like "Dog dogi=new Dog();", i am able to access all the mothods in Animal and Dog class but when i do it like "Animal ann = dogi;" i am only able to access all methods of Animal but not Dog why like "ann.Run():" ?
Questionc sharp programmingmembermisbahafridi26 Nov '12 - 7:39 
Confused | :confused:
what is partial overriding and full overriding in c#??
what the diffrence between these both???? plz reply quick!!!
GeneralMy vote of 4membernilesh.nildata31 Oct '12 - 0:07 
Its good one..
GeneralMy vote of 5memberRevaOnwards29 Oct '12 - 9:54 
very helpful for newbies
GeneralMy vote of 4membershak imran20 Sep '12 - 20:34 
It's good
QuestionInheritance and polymorphism in C #memberJyoti516 Sep '12 - 13:14 
Constructors of the base class cannot be inherited by the derived class.
Then how come, on executing the statement " Dog d1 = new Dog(); ", the base(ie Animal) class constructor also get called alongwith the derived (ie Dog ) class constructor.
  
  
   Output:  
               Animal Constructor.
               Dog Constructor.
AnswerRe: Inheritance and polymorphism in C #memberjagadesh43725 Mar '13 - 19:41 
When we are inheriting the Base class means we are able to access all the methods and variables in a base class. That means when we create the instance of the derived class it automatically creates the instance of base class.
GeneralMy vote of 3memberusrikanthvarma13 Aug '12 - 2:43 
Article is good but it needs to get into more depth.
GeneralMy vote of 3memberhareesh.devunoori3 Aug '12 - 4:34 
it's average
GeneralMy vote of 4memberApoorva Keshav12 Jul '12 - 17:55 
examples are easy and simple to understand
GeneralMy vote of 5memberTapan dubey11 Jun '12 - 3:16 
Perfect Explanation in very simple words.. very good article, thanks for sharing your knowledge with us.
 
Tapan Dubey
GeneralMy vote of 3membersankarrbs8 May '12 - 20:18 
ok
GeneralMy vote of 5memberTarun K.S7 Jul '11 - 4:48 
Excellent article to brush up basic concepts. Smile | :)
GeneralMy vote of 5memberkdchandima12 May '11 - 4:17 
I got the idea about polymorphism
GeneralVery Nice Articlemembergovind_ind12318 Apr '11 - 19:35 
Very Interesting Article.
QuestionDoubt abt new keywordmemberSrigurusankar27 Feb '11 - 19:33 
Hi Nish
Why we use NEW KEYWORD public new void Talk(). I read. but couldn't understand
Thanks
-Sankar.
AnswerRe: Doubt abt new keywordmemberTweakBird25 May '11 - 0:55 
New keyword is used to create a new definition of that method, field, or property on a derived class. In Dog class creating new definition of Talk() method. It was in super class(Animal)
Regards,
TweakBird
***** Posted 50000th post in GIT O_O ******

GeneralMy vote of 3memberSunnyBuzz28 Jul '10 - 22:30 
They define pollymorphism asual good...
 
Best of luck
QuestionIs it possible to do polymorphism with out inheritnace????memberamistry_petlad10 Jun '10 - 3:55 
Hi Nish,
 
Amit here,I wonder to know about polymorphism without inheritance is it possible?? and if yes can you explain in detail with example...
Thanks, I would appreciate if you can take some time on this....
GeneralUnable to cast object of type 'Inheritance.person' to type 'Inheritance.employee'.groupanup choudhari30 May '10 - 23:46 
Hi,
While assiging the refrence from on e object to other i am getting the above Error.

employee emp1 =(employee)new person(Date, email_address, Occupation);

emp1.display();
obj.display();
Please revert.
Laugh | :laugh:
General...member69er6 Feb '10 - 0:02 
nice...n easy. good stuff
GeneralGREATmembershanto01327 Aug '09 - 17:42 
NICE WORK BOSS
GeneralNice Articalmemberrk4dotnet1 Apr '09 - 1:32 
Hi this is very helped me thanx
Question.netmembersandik484 Jan '09 - 19:44 
i how connect to link b/w the sql and asp insert command
AnswerRe: .netmvpNishant 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 InheritancememberShiv...26 Aug '07 - 23:39 
I never seen such a simple explanation and easy understandable one.
 
thanks
 

 
Shiv...

Generalmade easy to undertandmemberpallavipatil0121 Jun '07 - 20:52 
thanx for giving such a simple example which made all concepts clear.
 
pallavi patil
GeneralOutput seems to have an errormemberComputerKat19 Jan '07 - 8:34 
Is that really the output? Shouldn't the output be:
 
//Output
Animal constructor
Dog constructor
Dog talk
Dog song
Animal says Hello
 
The talk() command should be overloaded along with the song().
GeneralRe: Output seems to have an errormemberpeter200210 Mar '07 - 11:49 
No, the article's output is right output for 2nd example is:
 
Animal constructor
Dog constructor
Animal talk
Dog song
Animal says Hello
 
because Dog class has public new void Talk() not override.
I complied and run the sample code and I had above answer.
Generalquestion about last examplememberdaddion30 Oct '06 - 16:52 

DundasSoftware du2 = new DundasSoftware("test",75);
 
//Output
75
test
 
How come this is what happened? Where did 75 print out come from? Thank you.
GeneralRe: question about last examplemembertbenda11 Dec '06 - 6:23 
public DundasSoftware(string s, int f) : this(f)
Notice the line above.
 
The bit after the colon instructs the constructor to call the
first constructor (the one with only one parameter.)
 
That constructor in turn calls the constructor for its base class, which finally prints out f.
Questionwhy the new modifier?memberlogistum29 Jul '06 - 11:22 
why did you put the new modifier on the dog subclass
 
public new void Talk()
 
is that necessary if the superclass does not have virtual
specified on the method signature
 
sdfgdf

AnswerRe: why the new modifier?memberberen77722 Aug '06 - 23:29 
That's correct. Have a look at this article on MSDN:
 
http://msdn2.microsoft.com/en-us/library/ms173152.aspx
 
"When the new keyword is used, the new class members are called instead of the base class members that have been replaced. Those base class members are called hidden members. Hidden class members can still be called if an instance of the derived class is cast to an instance of the base class."
GeneralGood tutorial; one questionmemberHuline31 Oct '05 - 7:38 
Hi Nish,
 
Can you explain more to me the difference between declaring objects this way
 
Animal a2 = new Dog();
 
versus this way
 
Dog d1 = new Dog();
 
...in terms of inheritance and polymorphism?
 

Thanks
GeneralRe: Good tutorial; one questionmembersikemullivan21 Dec '05 - 9:29 
I believe that if you add extra methods or variables to Dog that the base class Animal does not have... you create a different object that can not be cast as Animal.
 
Sully
Generalexcellentmemberhollyireland28 Oct '04 - 10:56 
You have jumped to the top of my favorite person list. Thanks. Smile | :)
 
Holly N Ireland
Software Engineer
GeneralRe: excellentstaffNishant S28 Oct '04 - 16:11 
hollyireland wrote:
You have jumped to the top of my favorite person list. Thanks.
 
Glad to hear that Smile | :)
 

My blog on C++/CLI, MFC/Win32, .NET - void Nish(char* szBlog);
My MVP tips, tricks and essays web site - www.voidnish.com

GeneralIt helped! ThankxmemberKavya Menon18 Sep '03 - 2:30 
Now I know what all that stuff was all about...Thanks a lot!
 
Smile | :)
 
Kavya

GeneralRe: It helped! ThankxeditorNishant S18 Sep '03 - 3:49 
Kavya Menon wrote:
Now I know what all that stuff was all about...Thanks a lot!
 
Hello
 
Glad to have been of help
 
Nish Smile | :)
 

Extending MFC Applications with the .NET Framework [NW] (coming soon...)
Summer Love and Some more Cricket [NW] (My first novel)
Shog's review of SLASMC [NW]
Come with me if you want to live

GeneralNice beginners article NishmemberBrian Delahunty28 Dec '02 - 8:06 
Hey Nish,
 
Nice beginners article. Smile | :)
 
The newbies will appreciate it Big Grin | :-D
 
Regards,
Brian Dela Sleepy | :zzz:
GeneralRe: Nice beginners article Nishmemberleppie28 Dec '02 - 8:50 
Brian Delahunty wrote:
The newbies will appreciate it
 
I think some oldies must read it too Unsure | :~
 
WebBoxes - Yet another collapsable control, but it relies on a "graphics server" for dynamic pretty rounded corners, cool arrows and unlimited font support.

GeneralRe: Nice beginners article NisheditorNishant S28 Dec '02 - 19:32 
leppie wrote:

I think some oldies must read it too

 
The anti-C# band-wagon guys eh? Uhm, yeah perhaps...
 
Nish
 

Author of the romantic comedy

Summer Love and Some more Cricket [New Win]

Review by Shog9
Click here for review[NW]

GeneralRe: Nice beginners article NishmemberBrian Delahunty8 Jan '03 - 1:46 
leppie wrote:
I think some oldies must read it too
 
Yeah. Very true Big Grin | :-D
 
Regards,
Brian Dela Smile | :)
GeneralRe: Nice beginners article NisheditorNishant S28 Dec '02 - 19:31 
Brian Delahunty wrote:
Nice beginners article.
 
The newbies will appreciate it

 
Thank you BRian Smile | :)
 
Nish
 

Author of the romantic comedy

Summer Love and Some more Cricket [New Win]

Review by Shog9
Click here for review[NW]

GeneralRe: Nice beginners article NishmemberBrian Delahunty8 Jan '03 - 1:44 
Nishant S wrote:
Thank you BRian
 
Your welcome Nish Smile | :)
 
Regards,
Brian Dela Smile | :)
GeneralRe: Nice beginners article NishsussAnonymous26 May '04 - 2:48 
>I'm an experience programmer but from time to time ,I need to revive my memory with
such a basic and very important knowlage.
Thank you.
 
So its not just for n00bs, which you obviously aren't...
GeneralA very good article !sussAnonymous22 Jul '02 - 4:34 
I'm an experience programmer but from time to time ,I need to revive my memory with
such a basic and very important knowlage.
Thank you.

GeneralRe: A very good article !editorNishant S23 Oct '02 - 22:03 
I am glad this was useful Smile | :)
 
Nish
 

Author of the romantic comedy

Summer Love and Some more Cricket [New Win]

Review by Shog9
Click here for review[NW]

GeneralRe: A very good article !sussAnonymous13 Jan '03 - 14:59 
I have read many articles on polymorphism. But yours is the BEST article I have come across.
Simply way of expressing complicated things..... Good job

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

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 10 Oct 2001
Article Copyright 2001 by Nish Sivakumar
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid