This is an extension of this questionand probably might even be a duplicate of some other question(If so, please forgive me). I see from MSDN that generics are usually used with collections
The most common use for generic
classes is with collections like
linked lists, hash tables, stacks,
queues, trees and so on where
operations such as adding and removing
items from the collection are
performed in much the same way
regardless of the type of data being
stored.
The examples I have seen also validate the above statement.
Can someone give a valid use of generics in a real-life scenario which does not involve any collections ?
Pedantically, I was thinking about making an example which does not involve collections
public class Animal<T>
{
public void Speak()
{
Console.WriteLine("I am an Animal and my type is " + typeof(T).ToString());
}
public void Eat()
{
//Eat food
}
}
public class Dog
{
public void WhoAmI()
{
Console.WriteLine(this.GetType().ToString());
}
}
and “An Animal of type Dog” will be
Animal<Dog> magic = new Animal<Dog>();
It is entirely possible to have Dog getting inherited from Animal (Assuming a non-generic version of Animal)Dog:Animal Therefore Dog is an Animal
Another example I was thinking was a BankAccount. It can be BankAccount<Checking>,BankAccount<Savings>. This can very well be Checking:BankAccount and Savings:BankAccount.
Are there any best practices to determine if we should go with generics or with inheritance ?
You’ll probably get some better answers, but meanwhile consider this:
Generic classes imply an “of” relation between the generic class and the parameter class.
All dogs are animals, so they share certain attributes/qualities with all other animals. If you use inheritance, then it is very easy to implement those common qualities in the Animal class, and add qualities at decendant classes. But if you implement it using
Animal (Of Dog), then:Animal (Of T)class. The Dog must be tied with the Animal in a parent-child relationship.Animal (Of T)class. It is actually a family of classes with a common behavior, not a superclass. You lose the benefit of dealing with Animals outside theAnimal (Of T)class.But here is how, IMHO, you should think of generics:
Think about a
MedicalDoctor(Of T)class.Veterinarian(Of T as Animal)would be inheriting fromMedicalDoctor(Of Animal).DogVeterinarianwould inherit fromVeterinarian(Of Dog).Key point: the generic class and the parameter class are not tightly-coupled and co-dependant, they co-exist.
BTW, if you want to see some good non-collection usage of generics, just notice the delegates we have: Action(Of T), Func(Of TResult), Comparison(Of T), EventHandler(Of TEventArgs), Converter(Of TSource, TResult)… and the interfaces: IEqualityComparer(Of T), IComparer(Of T)…