+92 332 4229 857 99ProjectIdeas@Gmail.com

Optional Parameters (C#.net)




Optional Parameters:
The following code shows you how you can use optional parameters, it can really help you in function overloading.

Code


// optional paramaters
// the optional parameter should be last in arguments
public int add(int n1, int n2, int n3 = 0) // here n3 is optional
{
    return n1 + n2 + n3;
}

public static void Main(string[] args)
{

   int result1 = add(2, 3);
   Console.WriteLine("The result of Add function is : " + result1);

   int result2 = add(2, 3, 4);
   Console.WriteLine("The result of Add function is : " + result2);

}

Output of the program is:
The result1 of Add function is : 5
The result2 of Add function is : 9


// if you assign the default value to z, then when you call it, will pick up the z  = 5 and add it. here y and z are optional.
public int add(int x, int y = 5 , int z = 7)
{
     return x + y + z;
}


You can also assign values to function like this,
   
// pick the default values of y and z from function
 Console.Write(add(x:3)); //answer is 15 because x = 3 , y = 5 and z = 7
 
 Console.Write(add(x:3,z:2)); // now,if you call it answer is : 10 because y = 5 in function

  Console.Write(add(x:4,y:4)); // now,if you call it answer is : 15 because z = 7 in function


// here str4 is optional here
public string concat(string str1, string str2, string str3, string str4 = null)
{
    return str1 + " " + str2 + " " + str3 + " " + str4;
}

public static void Main(string[] args)
{

   string result1 = concat("Pakistan", "Won", "Match");
   Console.WriteLine("The result of concatenates function is : " + result1);

   string result2 = concat("Pakistan", "Won", "A Cricket" , "Match");
   Console.WriteLine("The result of concatenates function is : " + result2);
}

Output of the program is:
The result1 of concat function is : Pakistan Won Match 
The result2 of concat function is : Pakistan Won A Cricket Match

0 comments: