Method Overloading means to have two or more methods with same name in the same class with different arguments. The benefit of method overloading is that it allows you to implement methods that support the same semantic operation but differ by argument number or type.
Important Points
Overloaded methods MUST change the argument list
Overloaded methods CAN change the return type
Overloaded methods CAN change the access modifier
Overloaded methods CAN declare new or broader checked exceptions
A method can be overloaded in the same class or in a subclass
You can not overload the function by differ only their return type . You can only overload the function in following ways
Parameter types
Number of parameters
Order of the parameters declared in the method
You can not come to know which function is actually called (if it was possible).
One more thing I would like to add is function overloading is providing a function with the same name, but with a different signature. but the return type of a method is not considered as a part of method's signature.
using System;
namespace ProgramCall
{
class Class1
{
public int Sum(int A, int B)
{
return A + B;
}
public float Sum(int A, float B)
{
return A + B;
}
}
class Class2 : Class1
{
public int Sum(int A, int B, int C)
{
return A + B + C;
}
}
class MainClass
{
static void Main()
{
Class2 obj = new Class2();
Console.WriteLine(obj.Sum(10, 20));
Console.WriteLine(obj.Sum(10, 15.70f));
Console.WriteLine(obj.Sum(10, 20, 30));
Console.Read();
}
}
}
Important Points
Overloaded methods MUST change the argument list
Overloaded methods CAN change the return type
Overloaded methods CAN change the access modifier
Overloaded methods CAN declare new or broader checked exceptions
A method can be overloaded in the same class or in a subclass
You can not overload the function by differ only their return type . You can only overload the function in following ways
Parameter types
Number of parameters
Order of the parameters declared in the method
You can not come to know which function is actually called (if it was possible).
One more thing I would like to add is function overloading is providing a function with the same name, but with a different signature. but the return type of a method is not considered as a part of method's signature.
using System;
namespace ProgramCall
{
class Class1
{
public int Sum(int A, int B)
{
return A + B;
}
public float Sum(int A, float B)
{
return A + B;
}
}
class Class2 : Class1
{
public int Sum(int A, int B, int C)
{
return A + B + C;
}
}
class MainClass
{
static void Main()
{
Class2 obj = new Class2();
Console.WriteLine(obj.Sum(10, 20));
Console.WriteLine(obj.Sum(10, 15.70f));
Console.WriteLine(obj.Sum(10, 20, 30));
Console.Read();
}
}
}
No comments:
Post a Comment