Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Generics or not?

Tags:

c#

.net

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.

like image 263
DotNetInfo Avatar asked Dec 04 '22 06:12

DotNetInfo


1 Answers

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.

like image 112
mjwills Avatar answered Dec 14 '22 02:12

mjwills