Challenge - 5 Problems
Generic Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of generic class with two type parameters
What is the output of the following C# program?
C Sharp (C#)
using System; class Pair<T, U> { public T First { get; set; } public U Second { get; set; } public Pair(T first, U second) { First = first; Second = second; } public void Print() { Console.WriteLine($"{First} and {Second}"); } } class Program { static void Main() { var pair = new Pair<int, string>(5, "hello"); pair.Print(); } }
Attempts:
2 left
💡 Hint
Look at how the generic parameters are used and printed in the Print method.
✗ Incorrect
The Pair class has two generic parameters T and U. The Print method prints First and Second separated by ' and '. Since First is 5 and Second is "hello", the output is "5 and hello".
❓ Predict Output
intermediate2:00remaining
Output of generic method with two parameters
What is the output of this C# program?
C Sharp (C#)
using System; class Utils { public static void Swap<T, U>(ref T a, ref U b) { Console.WriteLine($"Swapping {a} and {b}"); } } class Program { static void Main() { int x = 10; string y = "test"; Utils.Swap(ref x, ref y); } }
Attempts:
2 left
💡 Hint
Generic methods can have multiple type parameters and can accept different types.
✗ Incorrect
The Swap method prints the values of a and b. Since a is 10 and b is "test", it prints "Swapping 10 and test".
🔧 Debug
advanced2:00remaining
Identify the error in generic class instantiation
What error does the following code produce?
C Sharp (C#)
class Container<T, U> { public T Item1; public U Item2; } class Program { static void Main() { Container<int> c = new Container<int, string>(); } }
Attempts:
2 left
💡 Hint
Check how many generic parameters the class Container expects.
✗ Incorrect
The class Container requires two type parameters but only one is provided in the declaration, causing CS0305 error.
📝 Syntax
advanced2:00remaining
Which option correctly declares a generic class with two parameters?
Select the correct syntax to declare a generic class with two type parameters T and U.
Attempts:
2 left
💡 Hint
Generic parameters are separated by commas inside angle brackets.
✗ Incorrect
The correct syntax uses commas to separate generic parameters inside angle brackets: .
🚀 Application
expert2:00remaining
Determine the number of items in a generic dictionary
Given the following code, how many items are in the dictionary after execution?
C Sharp (C#)
using System.Collections.Generic; class Program { static void Main() { Dictionary<int, string> dict = new Dictionary<int, string>(); dict.Add(1, "one"); dict.Add(2, "two"); dict[3] = "three"; dict[2] = "deux"; } }
Attempts:
2 left
💡 Hint
Adding a key that already exists updates its value, not adds a new item.
✗ Incorrect
The dictionary has keys 1, 2, and 3. The value for key 2 is updated, so total items remain 3.