public static void MyMethod(params int[] numbers) { // Method implementation goes here }
public static int Sum(params int[] numbers) { int sum = 0; foreach (int number in numbers) { sum += number; } return sum; }
int result = Sum(1, 2, 3, 4, 5); Console.WriteLine(result); // Output: 15
public static string Concatenate(params string[] strings) { StringBuilder sb = new StringBuilder(); foreach (string s in strings) { sb.Append(s); } return sb.ToString(); }
string result = Concatenate("Hello", " ", "World", "!"); Console.WriteLine(result); // Output: Hello World!
public static int Multiply(params int[] numbers) { int product = 1; foreach (int number in numbers) { product *= number; } return product; } int result1 = Multiply(2, 3); int result2 = Multiply(4, 5, 6); Console.WriteLine(result1); // Output: 6 Console.WriteLine(result2); // Output: 120
public static void PrintStrings(params string[] strings) { foreach (string s in strings) { Console.WriteLine(s); } } PrintStrings("Hello", "World", "C#");
// With params keyword public static int Add(params int[] numbers) { int sum = 0; foreach (int number in numbers) { sum += number; } return sum; } // Without params keyword (multiple overloads) public static int Add(int a, int b) { return a + b; } public static int Add(int a, int b, int c) { return a + b + c; } public static int Add(int a, int b, int c, int d) { return a + b + c + d; }
using System.Diagnostics; public static void PrintNames(params string[] names) { foreach (string name in names) { Console.WriteLine(name); } } // Measure the time taken to execute the method with 'params' keyword Stopwatch sw = Stopwatch.StartNew(); PrintNames("Alice", "Bob", "Charlie"); sw.Stop(); Console.WriteLine("Time taken (ms): " + sw.ElapsedMilliseconds);
// This code will result in a compilation error public static void InvalidMethod(params int[] numbers, params string[] strings) { // Method implementation }
// This code will result in a compilation error public static void InvalidMethod(params int[,] matrix) { // Method implementation }
public static void PrintInfo(string title, params string[] items) { Console.WriteLine(title); foreach (string item in items) { Console.WriteLine(item } } PrintInfo("Shopping List:", "Apples", "Bananas", "Oranges");
int[] numbers = { 1, 2, 3, 4, 5 }; int sum = Sum(numbers); Console.WriteLine(sum); // Output: 15 Handle empty input: When working with the ‘params’ keyword, you should account for the possibility of receiving no arguments: public static void PrintArray(params int[] numbers) { if (numbers.Length == 0) { Console.WriteLine("No numbers to print."); return; } foreach (int number in numbers) { Console.Write(number + " "); } Console.WriteLine(); } PrintArray(); // Output: No numbers to print.