Thursday, October 20, 2011

.NET interview questions: - Uses of the Params Keyword in C#.

This is the one the typical .NET interview questions and also the favorable question of the interviewers.

Params: - The params keyword lets you specify a method parameter that takes an argument where the number of arguments is variable.

So, let’s take a scenario where we can have the use of the Params keyword.
Below is the scenario for the same.

    class Program
    {
        static void Main(string[] args)
        {
            int y = Add(10, 20);
            Console.WriteLine("The Addition of two Numbers is : " + y);
            Console.ReadLine();
        }
        static int Add(int Num1, int Num2)
        {
            return Num1 + Num2;
        }
    }

In the above code snippet you can see that I have created a function “Add”
which takes two parameters as “Num1” and “Num2” and return the addition of two numbers. The value for the 
parameters are been passed from the Main and it simply print the output to the screen of the “y” variable.

Now, simply just run your Application and will see the result like below diagram.



The above code snippet seems to be working fine but what if want to pass multiple arguments at a single instance. So, the Params Keyword helps us to achieve the above scenario in much better manner.

Let’s create a simple example to understand the use of Params Keyword in much better manner.
In order to perform practically you just need to follow the following steps.

Step1: - create a simple Console Application for that just open Visual Studio go to >> File >> New >> Project >> Windows >> Select Console Application.





Step2: - Now, simply just add the below Code Snippet in to Program.cs file of your Console Application.


    class Program
    {
        static void Main(string[] args)
        {
//Passed 5 different values.
            int y =  Add(10,20,30,40,50);
            Console.WriteLine("The Addition of  Numbers are : " + y);
            Console.ReadLine();
        }
//Created a listNumbers variable as declared as Params.
        static int Add(params int[] listNumbers)
        {
            int Total = 0;
            foreach (int i in listNumbers)
            {
                Total = i + Total;
            }
            return Total;
        }
    }

In the above code snippet you can see that I have created a function “Add” with a Variable “listNumbers” declared using params.

Now, simply just run your Console Application and will see the result like below diagram.


In the above diagram of output you can see the addition of the five numbers using params keyword.

If not understood from the above article, then see the following video on params keyword: -



Get our articles on  Most asked Dotnet interview question for preparation.

Regards,

See author’s other important Dotnet interview questions

No comments: