In this chapter you will learn:
- What is Function Overloading?
- Function Overloading with Programming Example
Function Overloading
In function overloading, a function works differently based on parameters. A single function can have different nature based on a number of parameters and types of parameters. For example, you have a function Sum() that accepts values as a parameter and print their addition. You can write multiple functions with name Sum() but the parameter signature must be different.
Programming Example
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Function_Overloading { class Program { static void Main(string[] args) { Calculator.sum(); Calculator.sum(5,4); Calculator.sum(9.3f, 8.6f); Calculator.sum("Hello World"); Console.Read(); } } static class Calculator { public static void sum() { Console.WriteLine("No Value Provided"); } public static void sum(int x, int y) { Console.WriteLine("Sum of {0} and {1} is {2}", x, y, (x + y)); } public static void sum(float x, float y) { Console.WriteLine("Sum of {0} and {1} is {2}", x, y, (x + y)); } public static void sum(string s) { Console.WriteLine("{0} - is not a numeric value", s); } } }
Output
No Value Provided
Sum of 5 and 4 is 9
Sum of 9.3 and 8.6 is 17.9
Hello World - is not a numeric value
_
Guidelines
When you are doing method overloading, must remember following guidelines:
- Methods must be different based on their signature like number of parameters and types of parameters.
- There is no limit for method overloading. You can write multiple methods with same name but the signature must be different.
Summary
In this chapter, you learned about Function Overloading in C#. In the next chapter, you will learn about Operator Overloading in C# with programming example.