Challenge - 5 Problems
Generic Constraints Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate2:00remaining
Output of generic method with class constraint
Consider this C# generic method with a where clause restricting T to classes:
What will be printed when calling
public void PrintTypeName<T>() where T : class { Console.WriteLine(typeof(T).Name); }What will be printed when calling
PrintTypeName<string>()?C Sharp (C#)
PrintTypeName<string>();
Attempts:
2 left
💡 Hint
Remember that typeof(T).Name returns the exact type name with correct casing.
✗ Incorrect
In C#, typeof(string).Name returns 'String' with capital S because it reflects the CLR type name, not the C# keyword.
📝 Syntax
intermediate2:00remaining
Identify the invalid generic constraint syntax
Which of the following generic method declarations has a syntax error in its where clause?
Attempts:
2 left
💡 Hint
Check if the constraint type is a valid generic constraint type.
✗ Incorrect
You cannot use a concrete type like 'int' as a generic constraint. Constraints must be class, struct, interface, or new().
🧠 Conceptual
advanced2:00remaining
Understanding multiple generic constraints
Given the generic class declaration:
Which of the following statements is true about T?
class Repository<T> where T : class, IDisposable, new() {}Which of the following statements is true about T?
Attempts:
2 left
💡 Hint
Look carefully at all constraints combined with commas.
✗ Incorrect
The where clause requires T to be a class (reference type), implement IDisposable, and have a parameterless constructor.
🔧 Debug
advanced2:00remaining
Why doesn't this generic method modify the caller's variable?
Examine this method:
Why doesn't this code modify the original item passed by the caller?
void Save<T>(T item) where T : new() { var instance = new T(); item = instance; }Why doesn't this code modify the original item passed by the caller?
C Sharp (C#)
void Save<T>(T item) where T : new() { var instance = new T(); item = instance; }
Attempts:
2 left
💡 Hint
Think about how method parameters behave in C#.
✗ Incorrect
In C#, method parameters are passed by value by default. Reassigning 'item' inside the method changes only the local copy and does not affect the variable in the calling code.
❓ optimization
expert2:00remaining
Optimizing generic constraints for performance
You have a generic method:
Which change to the where clause can improve performance by allowing the compiler to optimize better?
public void Process<T>(T item) where T : class { /* ... */ }Which change to the where clause can improve performance by allowing the compiler to optimize better?
Attempts:
2 left
💡 Hint
Value types avoid null checks and boxing, improving performance.
✗ Incorrect
Using
where T : struct restricts T to value types, which are stored on the stack and avoid null checks and boxing, improving performance.