What is the output of this C# program?
using System; class Program { static void PrintNumbers(params int[] numbers) { foreach (var num in numbers) { Console.Write(num + " "); } } static void Main() { PrintNumbers(1, 2, 3); } }
Remember, params allows passing multiple arguments as an array.
The method PrintNumbers accepts any number of integers using params. It prints each number followed by a space, so the output is 1 2 3 .
What will this program print?
using System; class Program { static void ShowItems(params string[] items) { foreach (var item in items) { Console.Write(item + ","); } } static void Main() { string[] fruits = {"apple", "banana"}; ShowItems(fruits); } }
Passing an array to a params parameter passes all elements as arguments.
The array fruits is passed to ShowItems which treats it as multiple arguments. It prints each fruit followed by a comma, resulting in apple,banana,.
What is the output of this program?
using System; class Program { static void Display(string title, params int[] numbers) { Console.Write(title + ": "); foreach (var n in numbers) { Console.Write(n + " "); } } static void Main() { Display("Numbers", 5, 10, 15); } }
The params parameter must be last and collects all extra arguments.
The method prints the title then all numbers separated by spaces. The output is Numbers: 5 10 15 .
What error will this code produce?
class Program { static void Test(params int[] numbers, string label) { } }
Check the position of the params parameter.
The params parameter must be the last in the method signature. Here it is not last, so the compiler gives an error.
Consider this method:
void PrintAll(params string[] items) { Console.WriteLine(items.Length); }What will be printed when calling PrintAll() with no arguments?
Think about what params does when no arguments are passed.
When no arguments are passed, the params array is an empty array, so items.Length is 0.