C# Overloaded Methods

C# Code Snippets Overloaded Methods
Share:

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.

Resulting output:

Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger