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

Generic class declaration in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Generic Class Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of a generic class instance
What is the output of this C# program using a generic class?
C Sharp (C#)
using System;

class Box<T>
{
    public T Content { get; set; }
    public Box(T content) { Content = content; }
    public override string ToString() => $"Box contains: {Content}";
}

class Program
{
    static void Main()
    {
        var box = new Box<int>(123);
        Console.WriteLine(box);
    }
}
ABox contains: System.Int32
BBox contains: 123
CBox contains: T
DCompilation error
Attempts:
2 left
💡 Hint
Look at how the generic type T is used and what value is passed to the constructor.
❓ Predict Output
intermediate
2:00remaining
Generic class with multiple type parameters
What will be the output of this C# program with a generic class having two type parameters?
C Sharp (C#)
using System;

class Pair<T1, T2>
{
    public T1 First { get; set; }
    public T2 Second { get; set; }
    public Pair(T1 first, T2 second) { First = first; Second = second; }
    public override string ToString() => $"({First}, {Second})";
}

class Program
{
    static void Main()
    {
        var pair = new Pair<string, double>("pi", 3.14);
        Console.WriteLine(pair);
    }
}
A(3.14, pi)
BCompilation error
C(System.String, System.Double)
D(pi, 3.14)
Attempts:
2 left
💡 Hint
Check the order of type parameters and constructor arguments.
🔧 Debug
advanced
2:00remaining
Identify the error in generic class declaration
What error does this C# code produce?
C Sharp (C#)
class Container<T>
{
    public T Value;
    public Container(T val)
    {
        Value = val;
    }
}
ASyntaxError: Missing semicolon after 'Value = val'
BTypeError: Cannot assign T to Value
CRuntime error: NullReferenceException
DNo error, compiles successfully
Attempts:
2 left
💡 Hint
Check punctuation carefully inside the constructor.
❓ Predict Output
advanced
2:00remaining
Output of generic class with method using type constraint
What is the output of this C# program using a generic class with a type constraint?
C Sharp (C#)
using System;

class Calculator<T> where T : struct
{
    public T Add(T a, T b)
    {
        dynamic x = a;
        dynamic y = b;
        return x + y;
    }
}

class Program
{
    static void Main()
    {
        var calc = new Calculator<int>();
        Console.WriteLine(calc.Add(5, 7));
    }
}
A12
BCompilation error due to dynamic usage
CRuntime error: InvalidCastException
D0
Attempts:
2 left
💡 Hint
The Add method uses dynamic to add two struct values.
🧠 Conceptual
expert
2:00remaining
Understanding generic class variance
Which statement about generic class variance in C# is correct?
AVariance allows changing the type parameter of a generic class at runtime.
BGeneric classes support covariance and contravariance on their type parameters by default.
COnly interfaces and delegates can declare variance with 'in' and 'out' keywords, not classes.
DVariance means a generic class can only accept reference types as type parameters.
Attempts:
2 left
💡 Hint
Think about where 'in' and 'out' keywords are allowed in C# generics.

Practice

(1/5)
1.

What is the main purpose of declaring a generic class in C# using <T>?

easy
A. To allow the class to work with any data type safely
B. To restrict the class to only one specific data type
C. To make the class run faster by avoiding type checks
D. To create multiple classes with different names automatically

Solution

  1. Step 1: Understand generic class purpose

    Generic classes use type parameters to work with any data type, improving code reuse and safety.
  2. Step 2: Compare options with generic concept

    Only To allow the class to work with any data type safely correctly states that generics allow safe use with any data type.
  3. Final Answer:

    To allow the class to work with any data type safely -> Option A
  4. Quick Check:

    Generic class purpose = safe, reusable code [OK]
Hint: Generics = flexible types for safe reuse [OK]
Common Mistakes:
  • Thinking generics restrict to one type
  • Believing generics improve speed by skipping checks
  • Confusing generics with automatic class creation
2.

Which of the following is the correct syntax to declare a generic class named Box with one type parameter?

?
easy
A. public class Box<T>() { }
B. public class Box<T> { }
C. public class Box(T) { }
D. public class Box[] { }

Solution

  1. Step 1: Recall generic class syntax

    Generic classes use angle brackets with type parameters: class ClassName<T>.
  2. Step 2: Check each option

    public class Box<T> { } matches correct syntax. Options A, B, and D have syntax errors or wrong symbols.
  3. Final Answer:

    public class Box<T> { } -> Option B
  4. Quick Check:

    Generic syntax = class Name<T> [OK]
Hint: Generic classes use angle brackets <> [OK]
Common Mistakes:
  • Using parentheses instead of angle brackets
  • Adding parentheses after class name
  • Using square brackets instead of angle brackets
3.

What will be the output of the following C# code?

public class Container<T> {
    public T Value;
    public Container(T value) { Value = value; }
    public override string ToString() => $"Value: {Value}";
}

var intBox = new Container<int>(10);
var strBox = new Container<string>("Hello");
Console.WriteLine(intBox);
Console.WriteLine(strBox);
medium
A. Value: 10 Value: Hello
B. Value: intBox Value: strBox
C. 10 Hello
D. Compilation error due to missing type constraints

Solution

  1. Step 1: Understand class behavior

    The class stores a value of type T and overrides ToString() to print "Value: {Value}".
  2. Step 2: Trace output of Console.WriteLine

    intBox.ToString() returns "Value: 10" and strBox.ToString() returns "Value: Hello".
  3. Final Answer:

    Value: 10 Value: Hello -> Option A
  4. Quick Check:

    ToString override prints value with prefix [OK]
Hint: ToString() shows formatted value, not variable name [OK]
Common Mistakes:
  • Expecting variable names instead of values
  • Ignoring ToString() override
  • Thinking type constraints are required here
4.

Identify the error in this generic class declaration and fix it:

public class Pair<T, U>
{
    public T First;
    public U Second;

    public Pair(T first, U second)
    {
        First = first;
        Second = second;
    }
}

var p = new Pair<string>(5, "test");
medium
A. Generic class cannot have two type parameters
B. Constructor parameters should be swapped
C. Missing type arguments when creating instance: use new Pair<int, string>(5, "test")
D. Fields First and Second must be private

Solution

  1. Step 1: Check instance creation syntax

    Generic classes require type arguments when instantiated unless using C# 7.1+ with target-typed new.
  2. Step 2: Identify missing type arguments

    The code uses new Pair<string>(5, "test") without specifying <int, string>, causing error.
  3. Final Answer:

    Missing type arguments when creating instance: use new Pair<int, string>(5, "test") -> Option C
  4. Quick Check:

    Generic instantiation needs type args [OK]
Hint: Always specify type parameters when creating generic instances [OK]
Common Mistakes:
  • Omitting type arguments on new
  • Thinking generic classes can't have multiple parameters
  • Changing constructor parameter order unnecessarily
5.

You want to create a generic class Cache<TKey, TValue> that stores key-value pairs and only allows reference types for TValue. Which declaration is correct?

hard
A. public class Cache<TKey, TValue> where TKey : struct { }
B. public class Cache<TKey, TValue> where TValue : struct { }
C. public class Cache<TKey, TValue> where TKey : class { }
D. public class Cache<TKey, TValue> where TValue : class { }

Solution

  1. Step 1: Understand type constraints

    To restrict a generic type to reference types, use where Type : class.
  2. Step 2: Apply constraint to TValue

    The question requires TValue to be a reference type, so constraint applies to TValue.
  3. Final Answer:

    public class Cache<TKey, TValue> where TValue : class { } -> Option D
  4. Quick Check:

    Reference type constraint = where TValue : class [OK]
Hint: Use 'where TValue : class' to restrict to reference types [OK]
Common Mistakes:
  • Applying constraint to wrong type parameter
  • Using 'struct' instead of 'class' for reference types
  • Omitting constraints when needed
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