OPTIONAL PARAMETERS
FOUR WAYS
1) Use parameter arrays
2) Method overloading
3) Specify parameter defaults
4) Use OptionalAttribute that is present in System.Runtime.InteropService namespace
1)Use parameter arrays
using System;
using System.Text;
namespace ConsoleApplication4
{
public class MainClass
{
public static void Main()
{
AddNumber(10, 20 new object[] {30,50,40});
}
public static void AddNumber(int firstNumber, int SecondNumber, params object[] restofNumbers)
{
int result = firstNumber + SecondNumber;
if(restofNumbers != null)
{
foreach(int i in restofNumbers)
{
result += i;
}
}
Console.WriteLine(“Sum = ” + result);
Console.ReadLine();
}
}
}
2) Making method parameters optional using Method overloading
using System;
using System.Text;
namespace ConsoleApplication4
{
public class MainClass
{
public static void Main()
{
AddNumber(10, 20, new int[] {30,40});
}
// over loading method
public static void AddNumber(int firstNumber, int SecondNumber)
{
AddNumber(firstNumber, SecondNumber, null);
}
public static void AddNumber(int firstNumber, int SecondNumber, params int[] restofNumbers)
{
int result = firstNumber + SecondNumber;
if(restofNumbers != null)
{
foreach(int i in restofNumbers)
{
result += i;
}
}
Console.WriteLine(“Sum = ” + result);
Console.ReadLine();
}
}
}
3) Specify parameter defaults
using System;
using System.Text;
namespace ConsoleApplication4
{
public class MainClass
{
public static void Main()
{
AddNumber(10, 20, new int[] {30,40});
}
// optional parameters appears after all the parameters
public static void AddNumber(int firstNumber, int SecondNumber, int[] restofNumbers = null)
{
int result = firstNumber + SecondNumber;
if(restofNumbers != null)
{
foreach(int i in restofNumbers)
{
result += i;
}
}
Console.WriteLine(“Sum = ” + result);
Console.ReadLine();
}
}
}
NAMED PARAMETERS
using System;
using System.Text;
namespace ConsoleApplication4
{
public class MainClass
{
public static void Main()
{
Test(1,c:20);
}
// optional parameters appears after all the parameters
public static void Test(int a, int b = 10, int c = 20)
{
Console.WriteLine(“a = ” + a);
Console.WriteLine(“b = ” + b);
Console.WriteLine(“c = ” + c);
Console.ReadLine();
}
}
}