1

This question is specifically about generic methods (not classes).

What is the difference between the following two statements?

public bool MyMethod<T>(T t) where T : IMyInterface {}

public bool MyMethod(IMyInterface t) { }

The first statement defines a generic method and constrains the type, the second one is a non generic method and specifies the type of the parameter. Why would you use one over the other?

Or, similar example:

public class LibraryItem
{
    public string Title;
    public int Stock;
}

public void CheckIn<T>(T item) where T : LibraryItem
{
    item.Stock += 1;
}

public void CheckIn2(LibraryItem item)
{
    item.Stock += 1;
}

Again, what would be the advantage of using the generic version over the non-generic version?

Olivier De Meulder
  • 2,493
  • 3
  • 25
  • 30

2 Answers2

3

There is not much difference with such simple constraints.

In the 1st example if the T is a struct, the non-generic method will cause boxing. The generic method doesn't require boxing.

Constraints are not limited to a single interface, so sometimes you cannot achieve the same functionality with a non-generic method.

Jakub Lortz
  • 14,616
  • 3
  • 25
  • 39
0

Output compiled executable could be different, but I cannot see any difference in the 2 versions from a programming point of view: in both cases you have to pass an IMyInterface object to call the function.

Except that... the generic seems to be overcomplicated with no real benefit.

You know you have to deal with some specific interface type as parameter, no need for generics.

Consider at opposite the framework class List<T>, that's a list that can handle only T objects: in this case, generics comes in hand, and using an interface would not.

Gian Paolo
  • 4,161
  • 4
  • 16
  • 34