How to make a function accepting variable arguments of same type in C#

Here is a simple way by which we can declare a function in C# which accepts variable arguments of a particular type. We have a keyword params in C# which we can use in the parameters in a function.

public class Util
    {
        public static List<int> AddIntegersToList(params int[] integerList)
        {
            List<int> numbers = new List<int>();
            foreach (int item in integerList)
            {
                numbers.Add(item);
            } return numbers;
        }
    }

Now this will accept an array of integers and thus the no of integers which can be passed here is not fixed and hence it fullfills our requirement of a function which can receive variable no of arguments of a single type.

Now for the above function we can use

List<int> listOfIntegers = Util.AddIntegersToList(2, 8, 9, 56, 77);

We can pass here any no of integers.


Boxing And Unboxing in C#

1. Boxing is when we convert a value type into reference type,when we are boxing we are creating reference variables which point to a new copy on the heap. 2. Unboxing is when we convert a reference type to a value type. 3. Best example of boxing and unboxing can be while we store integer variable which is a value type in a ArrayList which is a reference type. 4. And when we retrieve the value stored in ArrayList to an integer then we change a reference type to value type ie we do unboxing.

ArrayList myArrayList = new ArrayList();
Int n = 7;
myArrayList.Add(n);//Boxing of n
n = (int)myArrayList[0];//Unboxing of myArrayList[0]

Two uses of using keyword in C#

There are two uses of using keyword in C# i)Using as Directive in C# can be used for importing namespaces to your classes. ii)Another most useful advantage is it can be used in codeblocks what is does is it calls the Dispose() method automatically to release the resources and also automatically implements the try catch blocks for you.Here it is called a using statement.So the advantage is that we dont have to explicitly write a try-catch block and our code looks tidy.