Recall & Review
beginner
What is a generic method in C#?
A generic method is a method that is declared with type parameters, allowing it to work with any data type while maintaining type safety.
Click to reveal answer
beginner
How do you declare a generic method in C#?
You declare a generic method by adding type parameters in angle brackets after the method name, before the parameter list, like public T Echo<T>(T input).
Click to reveal answer
beginner
Example: What does this method do?
public T Echo<T>(T input) { return input; }
This method returns the same value it receives, and it works with any type because of the generic type parameter T.
Click to reveal answer
intermediate
Why use generic methods instead of object type parameters?
Generic methods keep type safety and avoid boxing/unboxing, so the compiler checks types and performance is better.
Click to reveal answer
intermediate
Can generic methods have constraints? Give an example.
Yes, constraints limit the types that can be used. Example: public T CreateInstance<T>() where T : new() { return new T(); } means T must have a parameterless constructor.
Click to reveal answer
How do you declare a generic method in C#?
✗ Incorrect
Generic methods declare type parameters in angle brackets after the method name, like .
What is the benefit of using generic methods?
✗ Incorrect
Generic methods allow any data type but keep type safety checked by the compiler.
Which of these is a valid generic method declaration?
✗ Incorrect
Option C correctly declares a generic method with type parameter T.
What does the constraint 'where T : new()' mean in a generic method?
✗ Incorrect
The 'new()' constraint requires T to have a public parameterless constructor.
Can generic methods be declared inside non-generic classes?
✗ Incorrect
Generic methods can be declared inside any class, generic or not.
Explain how to declare a generic method in C# and why it is useful.
Think about how you can write one method that works with many types safely.
You got /4 concepts.
Describe what constraints are in generic methods and give an example.
Constraints tell the compiler what kind of types can be used.
You got /3 concepts.