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

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

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Generic Method Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of a generic method call
What is the output of this C# program that uses a generic method to print the type and value?
C Sharp (C#)
using System;
class Program {
    static void PrintTypeAndValue<T>(T value) {
        Console.WriteLine($"Type: {typeof(T)}, Value: {value}");
    }
    static void Main() {
        PrintTypeAndValue(123);
        PrintTypeAndValue("hello");
    }
}
AType: System.Object, Value: 123\nType: System.Object, Value: hello
BType: T, Value: 123\nType: T, Value: hello
CCompilation error due to missing generic constraints
DType: System.Int32, Value: 123\nType: System.String, Value: hello
Attempts:
2 left
💡 Hint
Remember that the generic type T is inferred from the argument type.
🧠 Conceptual
intermediate
1:30remaining
Understanding generic method constraints
Which statement about generic method constraints in C# is true?
AGeneric method constraints can only specify that T must be a value type.
BYou can constrain a generic method type parameter to be a reference type using 'where T : class'.
CConstraints cannot be combined; you can only use one constraint per generic parameter.
DYou must always specify a constraint for every generic method parameter.
Attempts:
2 left
💡 Hint
Think about how you restrict types to reference types or value types.
❓ Predict Output
advanced
2:00remaining
Output of generic method with multiple type parameters
What is the output of this C# program using a generic method with two type parameters?
C Sharp (C#)
using System;
class Program {
    static void Swap<T, U>(ref T a, ref U b) {
        Console.WriteLine($"Before swap: a={a}, b={b}");
        var temp = a;
        a = (T)(object)b;
        b = (U)(object)temp;
        Console.WriteLine($"After swap: a={a}, b={b}");
    }
    static void Main() {
        int x = 5;
        string y = "10";
        Swap(ref x, ref y);
    }
}
ARuntime InvalidCastException
BCompilation error due to invalid cast
CBefore swap: a=5, b=10\nAfter swap: a=5, b=10
DBefore swap: a=5, b=10\nAfter swap: a=10, b=5
Attempts:
2 left
💡 Hint
Casting between unrelated types using (T)(object) can cause runtime errors.
🔧 Debug
advanced
1:30remaining
Identify the error in generic method declaration
What error does this C# code produce?
C Sharp (C#)
class Program {
    static void PrintValue<T>() {
        Console.WriteLine(value);
    }
    static void Main() {
        PrintValue<int>();
    }
}
ARuntime error: NullReferenceException
BCompilation error: Missing generic type constraint
CCompilation error: 'value' does not exist in the current context
DNo error, prints default value
Attempts:
2 left
💡 Hint
Check if the variable 'value' is declared or passed.
🧠 Conceptual
expert
2:00remaining
Generic method type inference behavior
Given the generic method declaration
void Display(T item) { Console.WriteLine(item); }

and the call
Display(null);

What happens when you compile this code in C#?
ACompilation error: Cannot infer type for T because null is ambiguous
BCompiles and prints an empty line
CCompiles and prints 'null'
DRuntime error: NullReferenceException
Attempts:
2 left
💡 Hint
Think about how the compiler infers generic types from null arguments.

Practice

(1/5)
1. What is the purpose of declaring a generic method in C# using <T>?
easy
A. To allow the method to work with any data type specified when called
B. To restrict the method to only work with integers
C. To make the method private
D. To declare a method that returns void only

Solution

  1. Step 1: Understand generic method declaration

    Generic methods use <T> to represent a placeholder for any type, making the method flexible.
  2. Step 2: Identify the purpose of <T>

    The <T> allows the method to accept or return any type specified at call time, improving reuse.
  3. Final Answer:

    To allow the method to work with any data type specified when called -> Option A
  4. Quick Check:

    Generic <T> means flexible type [OK]
Hint: Generic <T> means method works with any type [OK]
Common Mistakes:
  • Thinking <T> restricts to one type like int
  • Confusing generic methods with access modifiers
  • Assuming generic methods always return void
2. Which of the following is the correct syntax to declare a generic method named PrintItem that takes one parameter of type T?
easy
A. public void PrintItem<T>(item T) { Console.WriteLine(item); }
B. public <T> void PrintItem(T item) { Console.WriteLine(item); }
C. public void PrintItem<T>(T item) { Console.WriteLine(item); }
D. public void PrintItem(T item) { Console.WriteLine(item); }

Solution

  1. Step 1: Review generic method syntax

    The generic type parameter <T> must come immediately after the method name.
  2. Step 2: Check parameter declaration

    The parameter should be declared as type T, followed by the parameter name.
  3. Final Answer:

    public void PrintItem<T>(T item) { Console.WriteLine(item); } -> Option C
  4. Quick Check:

    Generic <T> after method name, parameter type T [OK]
Hint: Put <T> right after method name for generics [OK]
Common Mistakes:
  • Placing <T> before return type
  • Omitting <T> after method name
  • Swapping parameter type and name
3. What will be the output of the following code?
public class Program {
    public static void ShowType<T>(T value) {
        Console.WriteLine(typeof(T));
    }
    public static void Main() {
        ShowType(123);
        ShowType("hello");
    }
}
medium
A. 123 hello
B. System.Int32 System.String
C. T T
D. System.Object System.Object

Solution

  1. Step 1: Understand typeof(T) in generic method

    typeof(T) returns the actual type used when the method is called.
  2. Step 2: Analyze calls ShowType(123) and ShowType("hello")

    First call uses int (System.Int32), second uses string (System.String).
  3. Final Answer:

    System.Int32 System.String -> Option B
  4. Quick Check:

    typeof(T) shows actual type [OK]
Hint: typeof(T) prints actual type used at call [OK]
Common Mistakes:
  • Expecting value output instead of type
  • Thinking T is printed literally
  • Assuming typeof(T) always returns System.Object
4. Identify the error in this generic method declaration:
public void Swap<T>(T a, T b) {
    T temp = a;
    a = b;
    b = temp;
}
medium
A. Cannot declare variable temp of type T
B. Missing generic type declaration <T> after method name
C. Method must return a value to swap
D. Cannot swap values because parameters are passed by value

Solution

  1. Step 1: Check parameter passing

    Parameters a and b are passed by value, so swapping inside method won't affect caller.
  2. Step 2: Confirm generic syntax correctness

    The method correctly declares <T> after method name and uses T type variables.
  3. Final Answer:

    Cannot swap values because parameters are passed by value -> Option D
  4. Quick Check:

    Value parameters can't swap caller variables [OK]
Hint: Swap needs ref/out to affect caller variables [OK]
Common Mistakes:
  • Thinking generic syntax is wrong
  • Assuming temp can't be type T
  • Expecting method must return swapped values
5. You want to write a generic method FindMax that returns the maximum of two values of any type T. Which constraint should you add to T to make comparison possible?
hard
A. where T : IComparable<T>
B. where T : class
C. where T : new()
D. where T : struct

Solution

  1. Step 1: Understand comparison requirement

    To compare two values of type T, T must support comparison operations.
  2. Step 2: Identify suitable generic constraint

    IComparable<T> interface defines CompareTo method for comparing instances.
  3. Step 3: Review other constraints

    class restricts to reference types, new() requires parameterless constructor, struct restricts to value types but no comparison guarantee.
  4. Final Answer:

    where T : IComparable<T> -> Option A
  5. Quick Check:

    Use IComparable<T> to enable comparisons [OK]
Hint: Use IComparable<T> constraint for comparing generics [OK]
Common Mistakes:
  • Using class or struct constraints instead of IComparable
  • Forgetting to add any constraint
  • Assuming new() enables comparison
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