0
0
C Sharp (C#)programming~20 mins

Params keyword for variable arguments in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Params Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of method using params keyword

What is the output of this C# program?

C Sharp (C#)
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);
    }
}
ASystem.Int32[]
B1, 2, 3
C1 2 3
DError: params keyword not allowed
Attempts:
2 left
💡 Hint

Remember, params allows passing multiple arguments as an array.

Predict Output
intermediate
2:00remaining
Output when passing an array to a params parameter

What will this program print?

C Sharp (C#)
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);
    }
}
ASystem.String[],
Bapple,banana,
Capple, banana,
DError: Cannot convert string[] to params string[]
Attempts:
2 left
💡 Hint

Passing an array to a params parameter passes all elements as arguments.

Predict Output
advanced
2:00remaining
Output when mixing normal and params parameters

What is the output of this program?

C Sharp (C#)
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);
    }
}
ANumbers: 5 10 15
BNumbers: 5,10,15
CNumbers: System.Int32[]
DError: params must be last parameter
Attempts:
2 left
💡 Hint

The params parameter must be last and collects all extra arguments.

Predict Output
advanced
2:00remaining
What error occurs with params not last?

What error will this code produce?

C Sharp (C#)
class Program {
    static void Test(params int[] numbers, string label) {
    }
}
ACompile-time error: missing return type
BRuntime error: invalid params usage
CNo error, compiles fine
DCompile-time error: params must be last parameter
Attempts:
2 left
💡 Hint

Check the position of the params parameter.

🧠 Conceptual
expert
2:00remaining
How many items in params array when called with no arguments?

Consider this method:

void PrintAll(params string[] items) { Console.WriteLine(items.Length); }

What will be printed when calling PrintAll() with no arguments?

A0
B1
Cnull
DCompile-time error
Attempts:
2 left
💡 Hint

Think about what params does when no arguments are passed.