Blue Theme Orange Theme Green Theme Red Theme
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
6 Months Free & No Setup Fees ASP.NET Hosting!
Search :       Advanced Search »
Home » C# Language » Polymorphism in C#

Polymorphism in C#

In this article I will explain you about method overloading i.e. compile time polymorphism.

Author Rank :
Page Views : 40553
Downloads : 0
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


When a message can be processed in different ways is called polymorphism. Polymorphism means many forms.

 

Polymorphism is one of the fundamental concepts of OOP.

 

Polymorphism provides following features: 

  • It allows you to invoke methods of derived class through base class reference during runtime.
  • It has the ability for classes to provide different implementations of methods that are called through the same name.

Polymorphism is of two types: 

  1. Compile time polymorphism/Overloading
  2. Runtime polymorphism/Overriding

Compile Time Polymorphism

 

Compile time polymorphism is method and operators overloading. It is also called early binding.

 

In method overloading method performs the different task at the different input parameters.

 

Runtime Time Polymorphism

 

Runtime time polymorphism is done using inheritance and virtual functions. Method overriding is called runtime polymorphism. It is also called late binding.

 

When overriding a method, you change the behavior of the method for the derived class.  Overloading a method simply involves having another method with the same prototype.

 

Caution: Don't confused method overloading with method overriding, they are different, unrelated concepts. But they sound similar.

 

Method overloading has nothing to do with inheritance or virtual methods.

 

Following are examples of methods having different overloads:

 

void area(int side);

void area(int l, int b);

void area(float radius);

 

Practical example of Method Overloading (Compile Time Polymorphism)

 

using System;

 

namespace method_overloading

{

    class Program

    {

        public class Print

        {

           

            public void display(string name)

            {

                Console.WriteLine("Your name is : " + name);

            }

 

            public void display(int age, float marks)

            {

                Console.WriteLine("Your age is : " + age);

                Console.WriteLine("Your marks are :" + marks);

            }

        }

       

        static void Main(string[] args)

        {

 

            Print obj = new Print();

            obj.display("George");

            obj.display(34, 76.50f);

            Console.ReadLine();

        }

    }

}

 

Note: In the code if you observe display method is called two times. Display method will work according to the number of parameters and type of parameters.

 

When and why to use method overloading

 

Use method overloading in situation where you want a class to be able to do something, but there is more than one possibility for what information is supplied to the method that carries out the task.

 

You should consider overloading a method when you for some reason need a couple of methods that take different parameters, but conceptually do the same thing.

 

Method Overloading showing many forms.

 

using System;

 

namespace method_overloading_polymorphism

{

    class Program

    {

        public class Shape

        {

            public void Area(float r)

            {

                float a = (float)3.14 * r;

                // here we have used funtion overload with 1 parameter.

                Console.WriteLine("Area of a circle: {0}",a);

            }

 

            public void Area(float l, float b)

            {

                float x = (float)l* b;

                // here we have used funtion overload with 2 parameters.

                Console.WriteLine("Area of a rectangle: {0}",x);

 

            }

 

            public void Area(float a, float b, float c)

            {

                float s = (float)(a*b*c)/2;

                // here we have used funtion overload with 3 parameters.

                Console.WriteLine("Area of a circle: {0}", s);

            }

        }

 

        static void Main(string[] args)

        {

            Shape ob = new Shape();

            ob.Area(2.0f);

            ob.Area(20.0f,30.0f);

            ob.Area(2.0f,3.0f,4.0f);

            Console.ReadLine();

        }

    }

}

 

Things to keep in mind while method overloading

 

If you use overload for method, there are couple of restrictions that the compiler imposes.

 

The rule is that overloads must be different in their signature, which means the name and the number and type of parameters.

 

There is no limit to how many overload of a method you can have. You simply declare them in a class, just as if they were different methods that happened to have the same name.

 

Conclusion

 

You can read my other article on inheritance explaining method overriding.

 

Hope the article would have helped you in understanding polymorphism. Please feel free to contact me for feedback or comments you may have about this article.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Puran Mehra

Working as a Software professional. 

Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Team Foundation Server Hosting
Become a Sponsor
 Comments
This is NOT about Polymorphism by Michael On July 5, 2009
Please read: http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming

"Polymorphism is not the same as method overloading or method overriding[1] Polymorphism is only concerned with the application of specific implementations to an interface or a more generic base class. Method overloading refers to methods that have the same name but different signatures inside the same class. Method overriding is where a subclass replaces the implementation of one or more of its parent's methods. Neither method overloading nor method overriding are by themselves implementations of polymorphism"
Reply | Email | Modify 
Re: This is NOT about Polymorphism by Puran On July 6, 2009
I have gone through the link which you have provided. But the article which i have submited is polymorphism only.

The link which you have sent explain polymorphism is though interface only. I would like to know what are interface and can polymorphism can be implemented with interface only.

As per my knowledge interface allows multiple inheritance in C#. They can be used in polymorphism which in another way of implemention methods. Please help in avoiding confusion.

Would like to have a detailed explanation about polymorphism if I am wrong.
Reply | Email | Modify 
Re: Re: This is NOT about Polymorphism by Michael On July 6, 2009
No, your article descripe method overloading (see: http://en.wikipedia.org/wiki/Method_overloading) and not polymorphism. Your artikel is good but it have nothing to do with polymorphism. "Polymorphism allows the programmer to treat derived class members just like their parent class' members. More precisely, Polymorphism in object-oriented programming is the ability of objects belonging to different data types to respond to method calls of methods of the same name, each one according to an appropriate type-specific behavior. One method, or an operator such as +, -, or *, can be abstractly applied in many different situations. If a Dog is commanded to speak(), this may elicit a bark(). However, if a Pig is commanded to speak(), this may elicit an oink(). They both inherit speak() from Animal, but their derived class methods override the methods of the parent class; this is Overriding Polymorphism." 
Reply | Email | Modify 
Re: Re: Re: This is NOT about Polymorphism by Puran On July 6, 2009

This is the example of compile time polymorphism using method overloading. Check the msdn link

http://msdn.microsoft.com/en-us/library/ms173152(VS.80).aspx

See my other article link for runtime polymorphism which is method overriding.

http://www.c-sharpcorner.com/UploadFile/puranindia/InheritancePolymorphism05252009024608AM/InheritancePolymorphism.aspx?ArticleID=b455d67e-5a2b-49f2-b3c6-7add0c1545d7

Reply | Email | Modify 
This isn't Polymorphism in the general computer science sense, this is an example of Ad-hoc Polymorphism. by Larry On July 26, 2009

Good article but this isn't Polymorphism in the general computer science sense, this is an example of Ad-hoc Polymorphism.

A better example would be if Shape was an Abstract Class with the Abstract Method of Area. Then you would have Circle, Square, and Triangle who each are decedents of the Shape class. Each of these shape objects would also implement the abstract method Area as it pertained to them. Now to show Polymorphism I can have an ArrayList or List<Shape> with a mix of Circle Square and Triangle that iterate through and call area method and each would handle area as implemented for each shape. If you will notice we could use the common interface of Shape and it doesn’t matter what decedent we actually were using but they all knew how to handle Area.

Keep in mind you also have Parametric polymorphism which applies more to Generics.

Not to be rude but please update the title of your article to indicate Ad-hoc Polymorphism or correct your example: “Really not good to spread misinformation to the community may have to work with one of these people some day.” http://en.wikipedia.org/wiki/Type_polymorphism

Reply | Email | Modify 
Re: This isn't Polymorphism in the general computer science sense, this is an example of Ad-hoc Polymorphism. by Puran On July 26, 2009
Thanks for the information. People learn throught mistake and I don't mind learning.

You action will be appreciated if you help me in learning rather than debarding me from the community.

Would like to mention that community doen;t work on your statements and views. Microsoft itself have many errors which are corrected and rectified in due course.

Thanks,
Reply | Email | Modify 
type of parameters by A On August 9, 2009
Hi,

please can you give more details about this:

"The rule is that overloads must be different in their signature, which means the name and the number and type of parameters"

In the example , there is the same type float in three methods, what about the rule

Thank you
Reply | Email | Modify 
About OOPS by Jayendrasinh On June 11, 2011
nice
Reply | Email | Modify 
About OOPS by Jayendrasinh On June 11, 2011
this is compile time polymorphism. More about polymorphism check http://msdn.microsoft.com/en-us/library/ms173152%28v=vs.80%29.aspx
Reply | Email | Modify 
compile time polymorphism by lolaraknath On July 28, 2011
can we have method with same name and parameters but different return types,if its not whar type of error will it give
Reply | Email | Modify 
makeadvice dot com by prabhat On August 17, 2011
for polymorphism exapmle you can visit on http://makeadvice.com/blog/?p=64
Reply | Email | Modify 
Discover the top 5 tips for understanding .NET Interop
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.