Recall & Review
beginner
What is the purpose of the
where clause in C# generics?The
where clause sets rules on the types that can be used as generic arguments, ensuring they meet certain requirements like implementing an interface or having a parameterless constructor.Click to reveal answer
beginner
Which of these is a valid generic constraint in C#?
Examples include
where T : class (reference type), where T : struct (value type), where T : new() (has parameterless constructor), or where T : SomeInterface (implements interface).Click to reveal answer
intermediate
Explain the constraint
where T : new().It means the generic type <code>T</code> must have a public parameterless constructor, so you can create instances of <code>T</code> inside the generic class or method.Click to reveal answer
intermediate
Can you use multiple constraints on a single generic type parameter? How?
Yes. You separate constraints with commas in the
where clause, for example: where T : class, ISomeInterface, new() means T must be a reference type, implement ISomeInterface, and have a parameterless constructor.Click to reveal answer
beginner
What happens if you try to use a type that does not meet the generic constraints?
The code will not compile. The compiler checks the constraints and gives an error if the type argument does not satisfy them.
Click to reveal answer
What does
where T : struct mean in a generic constraint?✗ Incorrect
where T : struct restricts T to value types like int, double, or structs.
Which constraint ensures the generic type has a parameterless constructor?
✗ Incorrect
where T : new() requires a public parameterless constructor.
How do you specify that a generic type must implement an interface
IMyInterface?✗ Incorrect
The syntax is where T : IMyInterface to require implementation.
Can you combine multiple constraints on one generic type parameter?
✗ Incorrect
Multiple constraints are separated by commas in the where clause.
What will happen if you use a type that does not meet the generic constraints?
✗ Incorrect
The compiler enforces constraints and will not compile code that violates them.
Describe how to use the
where clause to restrict a generic type to reference types that implement an interface and have a parameterless constructor.Think about combining constraints separated by commas.
You got /4 concepts.
Explain why generic constraints are useful when writing generic classes or methods.
Consider what happens if you try to use a type that doesn't fit the expected pattern.
You got /4 concepts.