July 2019
Intermediate to advanced
410 pages
10h 32m
English
A generic defines a behavior that can be applied to a class. A commonly used form of this is in collections, where the same approach to handling an object can be applied regardless of the type of object. For example, a list of strings or a list of integers can be handled using the same logic without having to differentiate between the specific types.
Going back to pets, we could define a generic class for feeding a pet. This class simply feeds a pet given both the pet and some food, as shown in the following code:
public static class PetFeeder{ public static void FeedPet<TP, TF>(TP pet, TF food) where TP : PetAnimal where TF : IPetFood { pet.Feed(food); }}
There are a couple of interesting thing to point out here. First of all, ...
Read now
Unlock full access