About
In this code snippet, we will learn how to overload methods in C#.
Method overloading is when you make more than one method with the same name. The other method/methods must, however, have a different signature(different input parameters) so the compiler can differentiate between the versions.
You would make an overloaded method in the case you need it to perform a similar function to an already existing method. You can even call the original method in the overloaded method. By doing this you can avoid duplicating code.
Additionally, intellisense in Visual Studio will help you and show all the overloaded version of the method you are trying to invoke(see images below).
Let’s look at the code example below to see how to overload a method.
Code:
using System; namespace OverloadedMethods { class Program { static void Main(string[] args) { PrintText("Hi."); PrintText("Hello.", 5); Console.ReadLine(); } public static void PrintText(string text) { Console.WriteLine(text); } //Overloading PrintText(). //A method with the same name can have multiple implementations as long as the method signiture(the input parameters are different) is different. public static void PrintText(string text, int n) { for (int i = 0; i < n; i++) { //Console.WriteLine(text); PrintText(text); } } } }
As you can see intellisense in Visual Studio offers you the two different implementations of the method.