Post: [C#] Method Overloading and Optional Parameters
04-04-2015, 09:43 PM #1
jagex
Gym leader
(adsbygoogle = window.adsbygoogle || []).push({}); Method Overloading is basically a method that has different types parameters.

    
private void run()
{
double n1 = 0;
double n2 = 0;
double n3 = 0;
Console.WriteLine("Input some numbers");
n1 = double.Parse(Console.ReadLine());
n2 = double.Parse(Console.ReadLine());
n3 = double.Parse(Console.ReadLine());
Console.WriteLine("Answer is {0}: ", Calculate(n1, n2));
Console.WriteLine("Answer is {0}: ", Calculate(n1, n2, n3));


}
private double Calculate(double n1, double n2)
{
return n1 + n2;
}
private double Calculate(double n1, double n2, double n3)
{
return n1 + n2 + n3;
}


Calculate() has parameters for adding two numbers or three numbers. If you hover over "Calculate(n1, n2));" you can use the up and down arrow key to switch parameters.

Note: this does not work return types. Having two calculate methods but each with a different return type will not work

Optional Parameters is a method that contains parameters that are not mandatory. To create optional parameters you need to give them a default value and they have to be declared after the mandatory parameters.

    
private double Calculate(double n1, double n2, double n3 = 0, string message = "The Answer Is ")
{
Console.Write(message);
return n1 + n2 + n3;
}


As you can see I did not do anything with the message parameter.
    
Console.WriteLine("{0}: ", Calculate(n1, n2, n3 = 10));


You can also fill parameters by using their name followed by a colon. You can do this out order.
    
Console.WriteLine("{0}", Calculate(n2: n2, message: "Final Answer: ", n3: n3, n1: n1));


I did this because I finished the chapter on methods and thought making a tutorial would help me absorb what I learned :p. Hopefully this helps others as well.
Last edited by jagex ; 05-06-2015 at 03:55 AM.

The following user thanked jagex for this useful post:

Pichu

Copyright © 2024, NextGenUpdate.
All Rights Reserved.

Gray NextGenUpdate Logo