C#: Method Overloading and Overriding
Introduction
I have been talking with few guys who still holds some doubt, or rather get confused with Overloading and Overriding words in C#.
I understand that there are numerous examples that can be found over internet, but still I thought to add another. After reading this article a reader might get a bit comfortable with these two words. Lets understand first before we jump into examples.
Method Overloading
When multiple methods share a same name without effecting the definition of each other. Its simply you call the desired one and get your result. The only way to identify and distinguish between two different methods with same name is their parameters.
In other words, to overload methods, both methods should have same name, but they should differ in type of parameters, number of parameters, or even sequence of parameters.
So if we take below methods inside a class:
- void MyMethod();
- void MyMethod(int x);
- void MyMethod(int x, int y);
- void MyMethod(int x, string s);
- void MyMethod(string s,int x);
All above are examples of Method Overloading.
Method Overriding
When we talk about Overriding, we have to accept the presence of Inheritance. Override it self indicates you change an existing method definition. When a class is derived from a base class, and the derived class has a method name same as that present in the base class, then derived class Overrides the base class definition.
To do this, the base class method should be declared as virual, and the derived class method should have "override" keyword used before the method name.
Note: if you do neither declare base class method as virtual nor the derived class method with override keyword, the compiler will simply give a warning "DerivedClassMethod hides InheritedBaseClassMethod. Use the new keyword if hiding was intended."
If you do not mark a method as virtual in base class and try to override it in derived class, the compiler will prohibit you with compilation error.
Example
01.using System;
02.using System.Collections.Generic;
03.using System.Linq;
04.using System.Text;
05.using System.Threading.Tasks;
06.
07.namespace CSharpApplication
08.{
09. abstract class BaseClass
10. {
11. public virtual string show()
12. {
13. return "from Base Class";
14. }
15. }
16.
17. class DerivedClass : BaseClass
18. {
19. public override string show() // Method Overriding
20. {
21. return "from Derived Class";
22. }
23.
24. public string show(string msg) // Method Overloading
25. {
26. return "Hello :" + msg;
27. }
28. }
29. class Program
30. {
31. static void Main(string[] args)
32. {
33. DerivedClass ob1 = new DerivedClass();
34. Console.WriteLine(ob1.show());
35. Console.WriteLine(ob1.show("Overloading"));
36. Console.ReadKey();
37. }
38. }
39.}