Question 13


Question

Multiple Choice

You are creatng an applicaton that manages informaton about zoo animals. The applicaton includes a class named Animal and a method named Save.
The Save() method must be strongly typed. It must allow only types inherited from the Animal class that uses a constructor that accepts no parameters.
You need to implement the Save() method.
Which code segment should you use?

  • A. public static void Save<T>(T target) where T : new(), Animal
  • B. public static void Save<T>(T target) where T : Animal
  • C. public static void Save<T>(T target) where T : Animal, new()
  • D. public static void Save<T>(T target)

Answer:

C
Explanation
When you defne a generic class, you can apply restrictons to the kinds of types that client code can use for type arguments when it instantates your class. If client code tries to instantate your class by using a type that is not allowed by a constraint, the result is a compile-tme error. These restrictons are called constraints. Constraints are specifed by using the where contextual keyword.