Showing posts with label c# params array. Show all posts
Showing posts with label c# params array. Show all posts

Thursday, January 22, 2015

Params in C#

When you create a method, you usually know in advance the number of arguments that you will be passing to it, but this is not always the case. Sometime you will want to create a method that can be passed an arbitrary number of arguments.

For example: I want to create a method that find smallest from the set of values. Such type of method cannot create cannot be created using a normal parameters. Instead, you must use a special type of parameter that stands for an arbitrary number of parameters.
This is done by creating a params parameter.

Params modifier is used to declare an array parameter that will be able to receive zero or more arguments. The number of elements in the array will be equal to the number of arguments passed to the method. You program then accesses the array to obtain the arguments.

Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace use_params
{
    class smallest
    {
        public int smallval(params int[] nums)
        {
           
            if (nums.Length == 0)
            {
                Console.WriteLine("error no argument ");
                return 0;
            }
          int n = nums[0];
            for (int i = 1; i < nums.Length; i++)
            {
                if (nums[i] < n)
                {
                    n = nums[i];
                  
                }
            }
            return n;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            smallest obj = new smallest();
            int small;
            int a = 5, b = 10;
            small = obj.smallval(a, b);
            Console.WriteLine("smallest value is " + small);
            small = obj.smallval(a, b, 2);
            Console.WriteLine("smallest value of three argument is " + small);
            small = obj.smallval(a, b, 18, 24, 45, 1);
            Console.WriteLine("smallest value of six argument is " + small);
            int[] arg = { 12, 25, 36, 96, 56, 21 };
            small = obj.smallval(arg);
            Console.WriteLine("minimum value of args " + small);
           Console.Read();
        }
    }
}
 
Output


Note: Here above mention example smallval() is called, the arguments are passed to passed via the nums array. Length of the array equal to the array of elements.

                                                        Author-Satya Prakash

Notice: The last call to smallval(). Rather than being the values individually, it is passed an array containing the values. This is a perfectly legal. When a params parameter is created, it will accept either a variable-length list of argument or an array containing the arguments.