methodOverLoading.md - brainchildservices/curriculum GitHub Wiki

Slide 1

C# Method Overloading

What is polymorphism?

Polymorphism means the ability to take different forms. Method Overloading is a form of polymorphism.

What is Method Signature?
Method Signature includes parameters list i.e. the number of the parameters, order of the parameters, and data types of the parameters. So whatever comes inside the method parenthesis would define the signature of the method. image

Slide 2

What is method overloading?
Two or more than two methods having the same name but different parameters is what we call method overloading in C#. The program would decide which method it would call based on the arguments it has.
Example program: https://dotnetfiddle.net/K6hbks

How to achieve method overloading?
Method overloading can be achieved by the following:

  • By changing number of parameters in a method
  • By changing the order of parameters in a method
  • By using different data types for parameters

Slide 3

Why do we need Method Overloading?
The advantage of method overloading is that it increases the readability of the program because you don't need to use different names for same action.
Eg: We use the same seive to coarser particles from wheat flour and rice flour. wheat flour and rice flour are the parameters and the sieve is our method.

Can we overload method by changing the return type?
Ans: No. return type of a method is not part of the signature of the method. So we can't do method overloading if the method names and parameter list are same but with different return type.
So we basically cannot have 2 methods that have the same name unless their parameter list varies. Eg: Wrong syntax:
https://dotnetfiddle.net/J0U4e0

Slide 4

Exercise using method overloading.

Q1> Create a class Shapes. Create overload for method Area that returns the area of the shapes(square, rectangle & Trapezium.). Call the method and print the results.

Q2> Create class Calculator. Create overload for method Product that returns the product(multiplication) value.

  • With 2 integer parameter.
  • With 2 double parameter
  • With 2 integer and 1 double parameter
  • With 2 double and 1 integer parameter in the order double, double, integer parameter
  • With 2 double and 1 integer parameter in the order double, integer, double parameter
    Call all the methods in Main and print the result.

References: https://www.w3schools.com/cs/cs_method_overloading.asp
https://www.geeksforgeeks.org/c-sharp-method-overloading/
https://www.c-sharpcorner.com/UploadFile/0c1bb2/method-oveloading-and-overriding-C-Sharp/
https://www.tutorialspoint.com/What-is-method-overloading-in-Chash