Sudhir Dehade
Sudhir Dehade

Reputation: 109

What should I use in following context - Method Overloading or Using generics?

I have two approach below, I want to know which should I use?

Approach 1 : Using Overloading

public Color GetColor(int? Id)
        {
            return db.Colors.Find(Id);
        }
        public Color GetColor(string Name)
        {
            return db.Colors.Where(m => m.Name == Name).FirstOrDefault();
        }

Approach 2 : Using generics

 public Color GetColor<T>(T value)
        {
            var type = value.GetType();

            if (type == typeof(Int32))
            {
                return db.Colors.Find(value); // Data fetched using Id
            }
            else if (type == typeof(string))
            {
                return db.Colors.Where(m => m.Name == value.ToString()).FirstOrDefault();  // Data fetched using name
            }
            return null;
        }

Both the above approaches give the desired result, I just want to know the pros and cons of both, and which should I prefer?

Upvotes: 1

Views: 143

Answers (3)

Reza Jenabi
Reza Jenabi

Reputation: 4299

we usually use overloading If we need to do the same kind of the operation in different ways i.e. for different inputs.

I think it's better if you do a operation with different inputs

public int add(int a, int b)  //two int type Parameters method  
{    
    return a + b;    

}    
public int add(int a, int b,int c)  //three int type Parameters with same method same as above  
{    
    return a + b+c;    

}    
public float add(float a, float b,float c,float d)  //four float type Parameters with same method same as above two method 
{    
    return a + b+c+d;    

}  

Generics in C# is its most powerful feature. It allows you to define the type-safe data structures. This out-turn in a remarkable performance boost and high-grade code, because it helps to reuse data processing algorithms without replicating type-specific code.

I think The general class is best when used to classify the class as generic and reduce its code, but the method used above does not seem to reduce your code.

 public class GenericRepository<TEntity> where TEntity : class
{
    internal BlogContext blogContextlog;
    internal DbSet<TEntity> dbSet;

    public GenericRepository(BlogContext context)
    {
        this.blogContextlog = context;
        this.dbSet = context.Set<TEntity>();
    }

    public virtual IEnumerable<TEntity> Get()
    {
        IQueryable<TEntity> query = blogContextlog.Set<TEntity>().ToList();
    }

    public virtual TEntity GetByID(object id)
    {
        return blogContextlog.Find(id);
    }
}

Upvotes: 0

ProgrammingLlama
ProgrammingLlama

Reputation: 38795

I know not everyone approaches writing code in this way, but I feel that code should demonstrate the intent of the programmer wherever possible. Method signatures should typically offer enough information, without other comments, etc. to indicate what the method does.

My objection to using generics like this is that it does not convey this kind of information. Since it takes an unconstrainted generic parameter, T, one might conclude that any object can be passed to your generic method and that it will return a colour. Indeed, if this code was in a closed source library, how would the caller know what the actual implementation does?

The overload methods are superior in this respect. They convey intent clearly and work as you would expect them to, without having to delve into their source code to find out how they work.

As for performance, the overloads will be superior because the method overload will be chosen at compile time. In comparison, the generic method would be limited to checking the supplied types at runtime, which will be slower.

Upvotes: 4

Mureinik
Mureinik

Reputation: 311893

Generics are useful for when you want to write a piece of code, well, generically, but retain type safety. E.g., adding to a list has the exact same code regardless of what the list holds, but you can only add a string to a list of strings.

In the second snippet you shared the code is anything but generic - it explicitly checks the type of the argument passed to it (in runtime!), and only handles strings and integers. There's really no upside to this snippet, and you'd be better off sticking to the overloaded variant like your first snippet.

Upvotes: 5

Related Questions