Generics Questions and Answers
Practice ModeShowing 10 of 32 questions
Q11
For the code snippet given below, which of the following statements are valid?
public class MyContainer<T> where T: class, IComparable
{
//Insert code here
}
Class MyContainer requires that it's type argument must implement IComparable interface.
Compiler will report an error for this block of code.
There are multiple constraints on type argument to MyContainer class.
Class MyContainer requires that its type argument must be a reference type and it must implement IComparable interface.
Answer: Option B
Q12
Which of the following statements is valid about advantages of generics?
Answer: Option C
Q13
What is the main purpose of generics in C#?
Answer: Option B
Explanation: Generics allow type-safe data structures without committing to actual data types.
Q14
Which keyword is used to define a generic class in C#?
Answer: Option C
Explanation: The angle brackets <> are used with type parameters to define generics.
Q15
What is a constraint in C# generics?
Answer: Option B
Explanation: Constraints restrict the types that can be used as arguments for generic parameters.
Q16
Which of the following is a valid generic class definition?
Answer: Option A
Explanation: Generic classes use type parameters in angle brackets.
Q17
What does the "where T : class" constraint mean?
Answer: Option B
Explanation: This constraint restricts T to reference types only.
Q18
Which method correctly uses generics?
Answer: Option A
Explanation: Generic methods can be defined within both generic and non-generic classes.
Q19
What is the default value of a generic type parameter?
Answer: Option C
Explanation: The default keyword returns appropriate default values for value and reference types.
Q20
Which constraint ensures a type has a parameterless constructor?
Answer: Option B
Explanation: The new() constraint requires a public parameterless constructor.