Bird
Raised Fist0
C Sharp (C#)programming~20 mins

Why generics are needed in C Sharp (C#) - Challenge Your Understanding

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Generics Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2: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);
    }
}
A0
Bhello
C10
DRuntime error
Attempts:
2 left
💡 Hint
Look at how the code sums only integers in the list.
❓ Predict Output
intermediate
2: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);
    }
}
A30
B10 20
C20
DCompilation error
Attempts:
2 left
💡 Hint
Sum all integers in the list.
🔧 Debug
advanced
2: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);
    }
}
AIndexOutOfRangeException because of foreach
BInvalidCastException because "hello" cannot be cast to int
CNo error, output is 10
DNullReferenceException because list is null
Attempts:
2 left
💡 Hint
Check the type casting inside the foreach loop.
🧠 Conceptual
advanced
2:00remaining
Why use generics instead of non-generic collections?
Which of the following is the main reason to use generics in C# collections?
ATo avoid runtime errors by enforcing type safety at compile time
BTo make code run slower but use less memory
CTo allow storing any type without restrictions
DTo make code compatible only with older .NET versions
Attempts:
2 left
💡 Hint
Think about when errors happen with non-generic collections.
❓ Predict Output
expert
3: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);
    }
}
A
Type: T, Value: 123
Type: T, Value: abc
Type: T, Value: 3.14
BCompilation error due to generic method
C
Type: System.Object, Value: 123
Type: System.Object, Value: abc
Type: System.Object, Value: 3.14
D
Type: System.Int32, Value: 123
Type: System.String, Value: abc
Type: System.Double, Value: 3.14
Attempts:
2 left
💡 Hint
typeof(T) shows the actual type used when calling the method.

Practice

(1/5)
1. Why are generics useful in C# programming?
easy
A. They automatically fix bugs in the code.
B. They make the program run faster by using less memory.
C. They replace the need for classes and methods.
D. They allow writing code that works with any data type without duplication.

Solution

  1. Step 1: Understand the purpose of generics

    Generics let you write one version of code that works with many data types, avoiding repeated code.
  2. Step 2: Compare other options

    The other options describe incorrect benefits or misunderstand generics' role.
  3. Final Answer:

    They allow writing code that works with any data type without duplication. -> Option D
  4. Quick Check:

    Generics = Flexible code reuse [OK]
Hint: Generics = one code, many types [OK]
Common Mistakes:
  • Thinking generics improve speed directly
  • Believing generics fix bugs automatically
  • Confusing generics with replacing classes
2. Which of the following is the correct syntax to declare a generic class in C#?
easy
A. class MyClass<T> { }
B. class MyClass[] { }
C. class MyClass<T>[] { }
D. class MyClass<T> () { }

Solution

  1. Step 1: Recall generic class syntax

    In C#, generic classes use angle brackets with a type parameter, like class MyClass<T> { }.
  2. Step 2: Check other options

    The other options use invalid syntax: arrays or parentheses are incorrect here.
  3. Final Answer:

    class MyClass<T> { } -> Option A
  4. Quick Check:

    Generic class syntax uses <T> [OK]
Hint: Generic classes use angle brackets <T> [OK]
Common Mistakes:
  • Using square brackets instead of angle brackets
  • Adding parentheses after class name
  • Combining array syntax with generics incorrectly
3. What will be the output of this C# code?
List<int> numbers = new List<int>();
numbers.Add(5);
numbers.Add(10);
Console.WriteLine(numbers[1]);
medium
A. 0
B. 5
C. 10
D. Compilation error

Solution

  1. Step 1: Understand list indexing

    The list numbers has two elements: 5 at index 0 and 10 at index 1.
  2. Step 2: Identify the printed element

    numbers[1] accesses the second element, which is 10.
  3. Final Answer:

    10 -> Option C
  4. Quick Check:

    Index 1 in list = 10 [OK]
Hint: List index starts at 0, so index 1 is second item [OK]
Common Mistakes:
  • Confusing index 0 and 1
  • Expecting compilation error due to generics
  • Thinking default value 0 is printed
4. Identify the error in this generic method declaration:
public T GetItem<T>(T item) {
    return item;
}
medium
A. Missing return type before method name
B. No error, the method is correct
C. Generic type parameter should be after method name
D. Generic type parameter should be declared in class, not method

Solution

  1. Step 1: Review generic method syntax

    The method declares a generic type parameter T correctly after the method name and returns the item.
  2. Step 2: Check other options

    The other options misunderstand generic method syntax; the code is valid.
  3. Final Answer:

    No error, the method is correct -> Option B
  4. Quick Check:

    Generic method syntax is correct [OK]
Hint: Generic methods declare <T> after method name [OK]
Common Mistakes:
  • Thinking generic type must be declared at class level only
  • Confusing method return type with generic parameter
  • Missing angle brackets around T
5. You want to create a generic method that returns the default value of any type. Which code correctly implements this in C#?
hard
A. public T GetDefault<T>() { return default(T); }
B. public T GetDefault<T>() { return null; }
C. public T GetDefault() { return default; }
D. public T GetDefault<T>() { return new T(); }

Solution

  1. Step 1: Understand how to return default value for generic type

    In C#, default(T) returns the default value for any type T, including value types and reference types.
  2. Step 2: Analyze each option

    public T GetDefault<T>() { return default(T); } uses default(T) correctly. public T GetDefault<T>() { return null; } returns null which fails for value types. public T GetDefault() { return default; } lacks generic parameter <T>. public T GetDefault<T>() { return new T(); } tries to create new instance but fails for types without parameterless constructor.
  3. Final Answer:

    public T GetDefault<T>() { return default(T); } -> Option A
  4. Quick Check:

    Use default(T) for generic default value [OK]
Hint: Use default(T) to get default generic value [OK]
Common Mistakes:
  • Returning null for value types
  • Omitting generic type parameter
  • Assuming new T() always works
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard