Got a simple question regarding whether to use generics or not and if yes, is this the right way?
The normal non-generic version is as below:
public interface IFood
{
string name { get; set; }
}
public class Vegetables : IFood
{
#region IFood Members
public string name
{
get { return "Cabbage"; }
set{ }
}
#endregion
}
public class Cow
{
private IFood _food;
public Cow(IFood food)
{
_food = food;
}
public string Eat()
{
return "I am eating " + _food.name;
}
}
The generic version is as below:
public class Cow<T> where T : IFood
{
private T _food;
public Cow(T food)
{
_food = food
}
public string Eat()
{
return "I am eating " + _food.name;
}
}
Am I doing everything right in generic version? Is it necessary to use Generic version for future growth? This is just the simple mock up of the original scenario but it resembles completely.
I think its a bad idea in this specific example.
A List<int>
is often described as List of int.
A Cow<IFood>
is harder to describe - it certainly isn't a Cow of IFood. This isn't a slam dunk argument, but shows a potential problem.
MSDN states:
Use generic types to maximize code reuse, type safety, and performance.
In your example, the generic version has no more code reuse, no more type safety and no improved performance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With