Freshblood
Freshblood

Reputation: 6441

Is using a generic better here, or is the interface enough?

Are there any advantages to using the first, generic-based method instead of the second method which simply utilizes an interface?

class MyClass
{
    public static void Method<T>(T t) where T:IBar
    {            
    }

    public static void Method(IBar bar)
    {
    }
}

Upvotes: 1

Views: 93

Answers (3)

digEmAll
digEmAll

Reputation: 57220

In this case having a interface type as constraint is not useful.

But sometimes it is, e.g. :

interface IHasId
{
   public int Id { get; }
}

public static IList<int> GetIds<T>(IList<T> items) where T:IHasId
{            
    return items.Select(item => item.Id).ToList();
}

in this (very silly) case you have the advantage that you can pass a IList<IHasIdImplementation> while in non-generic case you would have to pass IList<IHasId>.

Upvotes: 1

Ken Smith
Ken Smith

Reputation: 20445

There are two scenarios where I've found I need to use generics in a method definition.

The first is when the return value needs to be specified by the generic type value. So when it's like:

public T Method1<T>(object someobject) where T:IBar;

The second scenario is when you need to use the type parameter (not just an interface) inside the method.

An example of both requirements is a GetModelByKey() method in a ViewModelFactory class. This class caches ViewModels by ViewModelType and KeyType, and the resulting method looks like:

public ViewModelType GetViewModelByKey<ViewModelType, KeyType>(KeyType key) 
        where ViewModelType : ViewModelBase, new()
    {
        IDictionary dictionary;
        var type = typeof(ViewModelType);
        if (!keyedViewModelDictionaries.TryGetValue(type, out dictionary))
        {
            dictionary = new Dictionary<KeyType, ViewModelType>();
            keyedViewModelDictionaries.Add(type, dictionary);
        }
        var viewModels = (Dictionary<KeyType, ViewModelType>)dictionary;
        ViewModelType vm;
        if (!viewModels.TryGetValue(key, out vm))
        {
            vm = new ViewModelType();
            vm.Initialize(this);
            viewModels.Add(key, vm);
        }
        return vm;
    }

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1039478

Personally, I don't see any advantage of using generics in this particular case.

Upvotes: 2

Related Questions