InterviewSolution
Saved Bookmarks
| 1. |
How can we use Param Arrays in C#? |
|
Answer» If you are not sure of the parameters in the arrays, then you can use the param type arrays. The param arrays hold n number of parameters. The following is an example: using System; namespace Application { class Example { public int Display(PARAMS int[] a) { int mul = 1; foreach (int i in a) { mul *= i; } RETURN mul; } } class DEMO { static void MAIN(string[] args) { Example ex = new Example(); int mul = ex.Display(3, 4, 5); Console.WriteLine("Result = {0}", mul); Console.ReadKey(); } } }The OUTPUT: Result = 60Here is another example of param arrays in C#: using System; namespace ArrayDemo { class Example { static int SumOfElements(params int[] p_arr) { int sum=0; foreach (int i in p_arr) { sum += i; } return sum; } static void Main(string[] args) { int sum=0; sum = SumOfElements(4, 8, 7, 3, 1); Console.WriteLine("Sum of 5 Parameters: {0}", sum); sum = SumOfElements(5, 7); Console.WriteLine("Sum of 2 Parameters: {0}", sum); sum = SumOfElements(10, 7, 9); Console.WriteLine("Sum of 3 Parameters: {0}", sum); } } }The output of the above program is as follows: Sum of 5 Parameters: 23 Sum of 2 Parameters: 12 Sum of 3 Parameters: 26 |
|