0
0
C Sharp (C#)programming~5 mins

Generic constraints (where clause) in C Sharp (C#) - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
AT must be a value type
BT must be a reference type
CT must have a parameterless constructor
DT must inherit from a class
Which constraint ensures the generic type has a parameterless constructor?
Awhere T : new()
Bwhere T : class
Cwhere T : struct
Dwhere T : IDisposable
How do you specify that a generic type must implement an interface IMyInterface?
Awhere T inherits IMyInterface
Bwhere T implements IMyInterface
Cwhere T : IMyInterface
Dwhere T : class
Can you combine multiple constraints on one generic type parameter?
ANo, only one constraint is allowed
BYes, but only two constraints max
COnly if they are interfaces
DYes, separated by commas
What will happen if you use a type that does not meet the generic constraints?
ACode compiles but throws runtime error
BCode does not compile
CCode runs but behaves unpredictably
DCode compiles with warning
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.