In complex applications written in C#, we may need many methods which do essentially
similar functions but are just different enough to be considered unique.
A D V E R T I S E M E N T
For example,
we may have to calculate a person's tax liability and would need to implement a method
for doing this calculation in our application program. However, there are many
different rules when it comes to tax calculations and they vary throughout the world.
While there may be many rules, one basic equation stays the same: Your net income
equals your gross income minus a computed tax amount. We would probably have to
implement different methods for each type of tax calculation. And, we could give each
method a unique name such as TaxCalc1, TaxCalc2, TaxCalc3, etc. But wouldn't it be
nice to just name the method TaxCalc and pass different arguments to it based on the
computation desired?
Syntax:
Public void functionName(int a, params int[] varParam);
Public void functionName(int a);
How does C# know which method to call? It's easy. It knows which method to invoke based
on the number and type of arguments passed to it. This is also referred to as the
signature of the method. If C# sees you are calling TaxCalc with four arguments, then
it will call that method with four receiving arguments. The methods are all very similar
however they are differ by the number of arguments used in the tax calculation.
Caveat
It is important to remember that C# determines which method to call based upon the
method's signature. If you were to define two methods with the same name and the same
number and type of passed arguments, you would get a compile-time error .
However, we can have two methods with the same name and the same number of arguments as
long as the argument types differ.
Method overloading is a powerful concept in C# in that it helps to simplify code
reusability and clarity. If our example method of TaxCalc was placed in a .dll file
somewhere, we would only have to remember that I have to call TaxCalc and only fill
in the appropriate arguments to pass.