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

Generic method declaration in C Sharp (C#) - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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#?
AAdd type parameters in angle brackets after the method name
BUse the keyword 'generic' before the method name
CDeclare the method inside a generic class only
DUse 'var' keyword for the method return type
What is the benefit of using generic methods?
AThey make the code run faster by skipping type checks
BThey allow working with any data type while keeping type safety
CThey only work with reference types
DThey replace the need for classes
Which of these is a valid generic method declaration?
Apublic GetValue<T>(T value) { return value; }
Bpublic T GetValue(value) { return value; }
Cpublic T GetValue<T>(T value) { return value; }
Dpublic T GetValue<T> { return value; }
What does the constraint 'where T : new()' mean in a generic method?
AT must be a reference type
BT must be a value type
CT must inherit from a specific class
DT must have a parameterless constructor
Can generic methods be declared inside non-generic classes?
AYes, generic methods can be inside any class
BNo, only generic classes can have generic methods
COnly static classes can have generic methods
DOnly abstract classes can have generic methods
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.