Saturday, 15 March 2014

Optional and Named parameters in c#

In this article we are going to see how to create a method with optional parameters and named parameters,
what is an optional parameter ? in general when a calling method doesn't pass any value to the method method itself takes the default value to the parameter, there is no force for user to pass that parameter.
What is named parameter ? named parameter means user can re-order the data pass to the method , by passing the value along with the parameter mentioned.

Let we see now a sample .



        static void Rundata(int a,int b,int c = 10,int d = 20)
        {
            Console.WriteLine(string.Format("a:{0},b:{1},c:{2},d:{3}", a, b, c, d));
        }

        static void Main(string[] args)
        {
            Rundata(a: 10, b: 20);
            Rundata(5,3);
            Rundata(d: 4, a: 2, b: 2);
            Rundata(1, 2, 3, 4);
            Console.Read();           
        }


Output:

a:10,b:20,c:10,d:20
a:5,b:3,c:10,d:20
a:2,b:2,c:10,d:4

a:1,b:2,c:3,d:4


if you see the above example Rundata method have the two optional parameters c,d which may user can pass or may not pass to the method at the time of execution. In the main method you can see the the method Rundata is called by various formats , there named parameters are used by passing the value specify with the parameter.

From this post you can see how to use the named parameters and optional parameters.

No comments:

Post a Comment