Challenge - 5 Problems
Generics Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of non-generic collection usage
What is the output of this C# code that uses a non-generic ArrayList to store integers and strings?
C Sharp (C#)
using System; using System.Collections; class Program { static void Main() { ArrayList list = new ArrayList(); list.Add(10); list.Add("hello"); int sum = 0; foreach (var item in list) { if (item is int) { sum += (int)item; } } Console.WriteLine(sum); } }
Attempts:
2 left
💡 Hint
Look at how the code sums only integers in the list.
✗ Incorrect
The ArrayList contains 10 and "hello". The loop adds only integers to sum, so sum is 10.
❓ Predict Output
intermediate2:00remaining
Output of generic List usage
What is the output of this C# code that uses a generic List to store integers?
C Sharp (C#)
using System; using System.Collections.Generic; class Program { static void Main() { List<int> list = new List<int>(); list.Add(10); list.Add(20); int sum = 0; foreach (int item in list) { sum += item; } Console.WriteLine(sum); } }
Attempts:
2 left
💡 Hint
Sum all integers in the list.
✗ Incorrect
The list contains 10 and 20. The sum is 30.
🔧 Debug
advanced2:00remaining
Why does this code cause a runtime error?
This code uses a non-generic ArrayList but throws an exception at runtime. Why?
C Sharp (C#)
using System; using System.Collections; class Program { static void Main() { ArrayList list = new ArrayList(); list.Add(10); list.Add("hello"); int total = 0; foreach (int item in list) { total += item; } Console.WriteLine(total); } }
Attempts:
2 left
💡 Hint
Check the type casting inside the foreach loop.
✗ Incorrect
The foreach tries to cast "hello" to int, causing InvalidCastException.
🧠 Conceptual
advanced2:00remaining
Why use generics instead of non-generic collections?
Which of the following is the main reason to use generics in C# collections?
Attempts:
2 left
💡 Hint
Think about when errors happen with non-generic collections.
✗ Incorrect
Generics enforce type safety at compile time, preventing runtime casting errors.
❓ Predict Output
expert3:00remaining
Output of generic method with type parameter
What is the output of this C# code using a generic method to print the type and value?
C Sharp (C#)
using System; class Program { static void PrintValue<T>(T value) { Console.WriteLine($"Type: {typeof(T)}, Value: {value}"); } static void Main() { PrintValue(123); PrintValue("abc"); PrintValue(3.14); } }
Attempts:
2 left
💡 Hint
typeof(T) shows the actual type used when calling the method.
✗ Incorrect
The generic method prints the actual type of each argument and its value.