The Wayback Machine - https://web.archive.org/web/20240915123321/https://www.geeksforgeeks.org/c-sharp-method-overloading/
Open In App

C# | Method Overloading

Last Updated : 30 Jun, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Method Overloading is the common way of implementing polymorphism. It is the ability to redefine a function in more than one form. A user can implement function overloading by defining two or more functions in a class sharing the same name. C# can distinguish the methods with different method signatures. i.e. the methods can have the same name but with different parameters list (i.e. the number of the parameters, order of the parameters, and data types of the parameters) within the same class. 

  • Overloaded methods are differentiated based on the number and type of the parameters passed as arguments to the methods.
  • You can not define more than one method with the same name, Order and the type of the arguments. It would be compiler error.
  • The compiler does not consider the return type while differentiating the overloaded method. But you cannot declare two methods with the same signature and different return type. It will throw a compile-time error. If both methods have the same parameter types, but different return type, then it is not possible.

Why do we need Method Overloading?

If we need to do the same kind of the operation in different ways i.e. for different inputs. In the example described below, we are doing the addition operation for different inputs. It is hard to find many different meaningful names for single action.

Different ways of doing overloading methods- 
Method overloading can be done by changing:  

  1. The number of parameters in two methods.
  2. The data types of the parameters of methods.
  3. The Order of the parameters of methods.

By changing the Number of Parameters 

C#




// C# program to demonstrate the function
// overloading by changing the Number
// of parameters
using System;
class GFG {
 
    // adding two integer values.
    public int Add(int a, int b)
    {
        int sum = a + b;
        return sum;
    }
 
    // adding three integer values.
    public int Add(int a, int b, int c)
    {
        int sum = a + b + c;
        return sum;
    }
 
    // Main Method
    public static void Main(String[] args)
    {
 
        // Creating Object
        GFG ob = new GFG();
 
        int sum1 = ob.Add(1, 2);
        Console.WriteLine("sum of the two "
                          + "integer value : " + sum1);
 
        int sum2 = ob.Add(1, 2, 3);
        Console.WriteLine("sum of the three "
                          + "integer value : " + sum2);
    }
}


Output: 

sum of the two integer value : 3
sum of the three integer value : 6

 

By changing the Data types of the parameters

C#




// C# program to demonstrate the function
// overloading by changing the Data types
//  of the parameters
using System;
class GFG {
 
    // adding three integer values.
    public int Add(int a, int b, int c)
    {
        int sum = a + b + c;
        return sum;
    }
 
    // adding three double values.
    public double Add(double a,
                      double b, double c)
    {
        double sum = a + b + c;
        return sum;
    }
 
    // Main Method
    public static void Main(String[] args)
    {
 
        // Creating Object
        GFG ob = new GFG();
 
        int sum2 = ob.Add(1, 2, 3);
        Console.WriteLine("sum of the three "
                          + "integer value : " + sum2);
        double sum3 = ob.Add(1.0, 2.0, 3.0);
        Console.WriteLine("sum of the three "
                          + "double value : " + sum3);
    }
}


Output: 

sum of the three integer value : 6
sum of the three double value : 6

 

By changing the Order of the parameters

C#




// C# program to demonstrate the function
// overloading by changing the
// Order of the parameters
using System;
class GFG {
 
    // Method
    public void Identity(String name, int id)
    {
 
        Console.WriteLine("Name1 : " + name + ", "
                        + "Id1 : " + id);
    }
     
    // Method
    public void Identity(int id, String name)
    {
 
        Console.WriteLine("Name2 : " + name + ", "
                        + "Id2 : " + id);
    }
 
    // Main Method
    public static void Main(String[] args)
    {
 
        // Creating Object
        GFG obj = new GFG();
 
        obj.Identity("Akku", 1);
        obj.Identity(2, "Abby");
    }
}


Output:

Name1 : Akku, Id1 : 1
Name2 : Abby, Id2 : 2

What happens when method signature is same and the return type is different?
The compiler will give error as the return value alone is not sufficient for the compiler to figure out which function it has to call. Only if both methods have different parameter types (so, they have the different signature), then Method overloading is possible.

Example:

C#




// C# program to show error when method signature
// is the same and the return type is different.
using System;
class GFG {
 
    // adding two integer value.
    public int Add(int a, int b)
    {
 
        int sum = a + b;
        return sum;
    }
 
    // adding three integer value.
    public double Add(int a, int b)
    {
        double sum = a + b + 0.0;
        return sum;
    }
 
    // Main Method
    public static void Main(String[] args)
    {
 
        // Creating Object
        GFG ob = new GFG();
 
        int sum1 = ob.Add(1, 2);
        Console.WriteLine("sum of the two "
                          + "integer value :" + sum1);
 
        int sum2 = ob.Add(1, 2);
        Console.WriteLine("sum of the three "
                          + "integer value :" + sum2);
    }
}


Compile Time Error:

prog.cs(15,19): error CS0111: A member `GFG.Add(int, int)’ is already defined. Rename this member or use different parameter types 
prog.cs(7,16): (Location of the symbol related to previous error)

 



Previous Article
Next Article

Similar Reads

C# | Operator Overloading
Prerequisite: Operators in C# The concept of overloading a function can also be applied to operators. Operator overloading gives the ability to use the same operator to do various operations. It provides additional capabilities to C# operators when they are applied to user-defined data types. It enables to make user-defined implementations of vario
4 min read
C# | Constructor Overloading
Prerequisite: Constructors in C# It is quite similar to the Method Overloading. It is the ability to redefine a Constructor in more than one form. A user can implement constructor overloading by defining two or more constructors in a class sharing the same name. C# can distinguish the constructors with different signatures. i.e. the constructor mus
8 min read
C# | Overloading of Indexers
Prerequisite: Indexers in C# Like functions, Indexers can also be overloaded. In C#, we can have multiple indexers in a single class. To overload an indexer, declare it with multiple parameters and each parameter should have a different data type. Indexers are overloaded by passing 2 different types of parameters. It is quite similar to method over
3 min read
Difference between Method Overriding and Method Hiding in C#
Method Overriding is a technique that allows the invoking of functions from another class (base class) in the derived class. Creating a method in the derived class with the same signature as a method in the base class is called Method Overriding. In simple words, Overriding is a feature that allows a subclass or child class to provide a specific im
4 min read
C# | Uri.MakeRelativeUri(Uri) Method
Uri.MakeRelativeUri(Uri) Method is used to determine the difference between two Uri instances. Syntax: public Uri MakeRelativeUri (Uri uri); Here, it takes the URI to compare to the current URI. Return Value: If the hostname and scheme of this URI instance and uri are the same, then this method returns a relative Uri that, when appended to the curr
3 min read
Array.GetValue() Method in C# with Examples | Set - 1
Array.GetValue() Method in C# is used to gets the value of the specified element in the current Array. There are total 8 methods in the overload list of this method which are as follows: Array.GetValue(Int32, Int32) Array.GetValue(Int64, Int64) Array.GetValue(Int32) Array.GetValue(Int64) Array.GetValue(Int32, Int32, Int32) Array.GetValue(Int64, Int
4 min read
C# | CharEnumerator.MoveNext() Method
CharEnumerator.MoveNext() Method is used to increments the internal index of the current CharEnumerator object to the next character of the enumerated string. Syntax: public bool MoveNext(); Return Value: This method returns the boolean value true value if the index is successfully incremented and within the enumerated string otherwise, false. Belo
2 min read
C# | Math.IEEERemainder() Method
In C#, IEEERemainder() is a Math class method which is used to return the remainder resulting from the division of a specified number by another specified number. Syntax: public static double IEEERemainder (double a, double b); Parameters: a: It is the dividend of type System.Double.b: It is the divisor of type System.Double. Return Type: This meth
2 min read
C# | Substring() Method
In C#, Substring() is a string method. It is used to retrieve a substring from the current instance of the string. This method can be overloaded by passing the different number of parameters to it as follows: String.Substring(Int32) Method String.Substring(Int32, Int32) Method String.Substring Method (startIndex) This method is used to retrieves a
3 min read
C# Program to Demonstrate the Use of Exit() Method of Environment Classhttps://origin.geeksforgeeks.org/?p=705454
Environment Class provides information about the current platform and manipulates, the current platform. The Environment class is useful for getting and setting various operating system-related information. We can use it in such a way that retrieves command-line arguments information, exit codes information, environment variable settings informatio
3 min read
C# | IndexOfAny() Method
In C#, IndexOfAny() method is a String Method. It is used to search the specified character index present in the string which will be the first occurrence from start index. It returns index as an integer value. This method can be overloaded by changing the number of arguments passed to it. IndexOfAny Method (Char[])IndexOfAny Method (Char[], Int32)
7 min read
C# | CharEnumerator.GetType() Method
CharEnumerator.GetType() Method is used to get the type of the current instance. This method is inherited from the Object Class. Syntax: public Type GetType(); Return Value: This method returns the exact runtime type of the current instance. Below are the programs to illustrate the use of CharEnumerator.GetType() Method:+ Example 1: // C# program t
2 min read
File.GetLastWriteTimeUtc() Method in C# with Examples
File.GetLastWriteTimeUtc(String) is an inbuilt File class method which is used to return the date and time, in coordinated universal time (UTC), that the specified file or directory was last written to.Syntax: public static DateTime GetLastWriteTimeUtc (string path); Parameter: This function accepts a parameter which is illustrated below: path: Thi
2 min read
MathF.Sin() Method in C# with Examples
MathF.Sin(Single) is an inbuilt MathF class method which returns the sine of a given float value argument(specified angle). Syntax: public static float Sin (float x); Here, x is the angle(measured in radian) whose sine is to be returned and the type of this parameter is System.Single. Return Value: This method will return the sine of x of type Syst
2 min read
Double.CompareTo Method in C# with Examples
Double.CompareTo Method is used to compare the current instance to a specified object or Double object. It will return an integer which shows whether the value of the current instance is greater than, less than or equal to the value of the specified object or Double object. There are 2 methods in the overload list of this method as follows: Compare
5 min read
C# | Graphics.DrawLine() Method | Set - 1
Graphics.DrawLine() Method is used to draw a line connecting the two points specified by the coordinate pairs. There are 4 methods in the overload list of this method as follows: DrawLine(Pen, PointF, PointF) Method DrawLine(Pen, Int32, Int32, Int32, Int32) Method DrawLine(Pen, Single, Single, Single, Single) Method DrawLine(Pen, Point, Point) Meth
4 min read
UInt16.GetHashCode Method in C# with Examples
UInt16.GetHashCode method is used to get the HashCode for the current UInt16 instance. Syntax: public override int GetHashCode (); Return Value: This method returns a 32-bit signed integer hash code. Below programs illustrate the use of the above discussed-method: Example 1: // C# program to illustrate the // UInt16.GetHashCode() Method using Syste
1 min read
Stack.Peek Method in C#
This method(comes under System.Collections namespace) is used to return the object at the top of the Stack without removing it. This method is similar to the Pop method, but Peek does not modify the Stack. Syntax: public virtual object Peek (); Return Value: It returns the Object at the top of the Stack. Exception: Calling Peek() method on empty st
2 min read
C# | IsNullOrEmpty() Method
In C#, IsNullOrEmpty() is a string method. It is used to check whether the specified string is null or an Empty string. A string will be null if it has not been assigned a value. A string will be empty if it is assigned "" or String.Empty (A constant for empty strings). Syntax: public static bool IsNullOrEmpty(String str) Explanation: This method w
2 min read
C# | Math.Sign() Method
In C#, Sign() is a math class method which returns an integer that specify the sign of the number. This method can be overloaded by changing the data type of the passed arguments as follows: Math.Sign(Decimal): Returns the integer that specifies the sign of a decimal number. Math.Sign(Double): Returns the integer that specifies the sign of a double
3 min read
Int64.CompareTo Method in C# with Examples
Int64.CompareTo Method is used to compare the current instance to a specified object or Int64 and returns a sign of their relative values. There are 2 methods in the overload list of this method as follows: CompareTo(Int64) Method CompareTo(Object) Method Int64.CompareTo(Int64) Method This method is used to compare the current instance to a specifi
4 min read
C# | PadRight() Method
In C#, PadRight() is a string method. This method is used to left-aligns the characters in String by padding them with spaces or specified character on the right, for a specified total length. This method can be overloaded by passing different parameters to it. String.PadRight Method(Int32)String.PadRight Method(Int32, Char)String.PadRight Method(I
4 min read
C# | EndsWith() Method
In C#, EndsWith() is a string method. This method is used to check whether the ending of the current string instance matches with a specified string or not. If it matches, then it returns the string otherwise false. Using "foreach" loop, it is possible to check many strings. This method can be overloaded by passing different type and number of argu
5 min read
C# | Char.CompareTo() Method
In C#, Char.CompareTo() is a System.Char struct method which is used to compare this instance of a specified object or value type and check whether the given instance is precedes, follow, or appears in the same position in the sort order as the specified object or value type. This method can be overloaded by passing the different type of arguments
3 min read
C# | Char.IsUpper() Method
In C#, Char.IsUpper() is a System.Char struct method which is used to check whether a Unicode character can be categorized as an uppercase letter or not. Valid uppercase letters will be the members of the UnicodeCategory: UppercaseLetter. This method can be overloaded by passing different type and number of arguments to it. Char.IsUpper(Char) Metho
3 min read
C# | BitConverter.ToSingle() Method
This method is used to returns a single-precision floating-point number converted from four bytes at a specified position in a byte array. Syntax: public static float ToSingle (byte[] value, int startIndex); Parameters: value: It is an array of bytes. startIndex: It is the starting position within value. Return Value: This method returns a single-p
6 min read
C# | ToLower() Method
In C#, ToLower() is a string method. It converts every character to lowercase (if there is a lowercase character). If a character does not have a lowercase equivalent, it remains unchanged. For example, special symbols remain unchanged. This method can be overloaded by passing the different type of arguments to it. String.ToLower() Method This meth
3 min read
C# | ToUpper() Method
In C#, ToUpper() is a string method. It converts every characters to uppercase (if there is an uppercase version). If a character does not have an uppercase equivalent, it remains unchanged. For example, special symbols remain unchanged. This method can be overloaded by passing different type of arguments to it. String.ToUpper() Method This method
2 min read
C# | Copy() Method
In C#, Copy() is a string method. It is used to create a new instance of String with the same value for a specified String. The Copy() method returns a String object, which is the same as the original string but represents a different object reference. To check its reference, use assignment operation, which assigns an existing string reference to a
2 min read
MathF.Truncate() Method in C# with Examples
In C#, MathF.Truncate(Single) is a MathF class method which is used to compute an integral part of a specified single number or single-precision floating-point number.Syntax: public static float Truncate (float x); Parameter: x: It is the specified number which is to be truncated and type of this parameter is System.Single. Return Type: This method
1 min read
Article Tags :