Challenge - 5 Problems
Generic Method Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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"); } }
Attempts:
2 left
💡 Hint
Remember that the generic type T is inferred from the argument type.
✗ Incorrect
The generic method PrintTypeAndValue infers T from the argument type. For 123, T is int (System.Int32). For "hello", T is string (System.String). So the output shows the actual types and values.
🧠 Conceptual
intermediate1:30remaining
Understanding generic method constraints
Which statement about generic method constraints in C# is true?
Attempts:
2 left
💡 Hint
Think about how you restrict types to reference types or value types.
✗ Incorrect
In C#, you can use 'where T : class' to restrict T to reference types. You can also use 'where T : struct' for value types. Multiple constraints can be combined. Constraints are optional.
❓ Predict Output
advanced2: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); } }
Attempts:
2 left
💡 Hint
Casting between unrelated types using (T)(object) can cause runtime errors.
✗ Incorrect
The cast (T)(object)b tries to cast string "10" to int, which causes a runtime InvalidCastException.
🔧 Debug
advanced1: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>(); } }
Attempts:
2 left
💡 Hint
Check if the variable 'value' is declared or passed.
✗ Incorrect
The method tries to print 'value' but no variable named 'value' is declared or passed, causing a compilation error.
🧠 Conceptual
expert2:00remaining
Generic method type inference behavior
Given the generic method declaration
and the call
What happens when you compile this code in C#?
void Display(T item) { Console.WriteLine(item); }
and the call
Display(null);
What happens when you compile this code in C#?
Attempts:
2 left
💡 Hint
Think about how the compiler infers generic types from null arguments.
✗ Incorrect
The compiler cannot infer the type parameter T from a null literal alone because null can be any reference type, so it causes a compilation error.