Pages

Search

Monday, April 9, 2012

Optional and Named Parameters – C#


Visual studio 2010 C#, has extended the capability of calling a function with its argument based on name and also can omit the optional parameters which are set with default value in the function declaration.
Below example demonstrates the same.
Program.cs
  class Program
    {
        static void Main(string[] args)
        {
            try
            {
                //calling the function normally
                Console.WriteLine(CaculateArea(10, 20, "Rectangle 1"));

                //calling the function providing only "length" as named parameter and others will be default
                //which are optional
                Console.WriteLine(CaculateArea(length: 100));

                //calling the function sending all the arguments as named parameters whose order need
                //not be same as arguments order in the calling function.
                Console.WriteLine(CaculateArea(name: "Rectangle 2", width: 100, length: 200));
            }
            catch (Exception exp)
            {
                Console.WriteLine("Error : " + exp.Message);
            }
            Console.Read();
        }

        //function which width and name with default values which are like optional parameters.
        //optional parameters should always be declared at the end after the actual parametes.
        static string CaculateArea(int length, int width = default(int), string name = "No Name")
        {
            return string.Format("The area of \"{0}\" is {1}", name, length * width);
        }
    }

Output:



No comments:

Post a Comment