5

I don't really understand what is the difference between:

private void Send<T>(T packet) where T : IPacket

and

private void Send(IPacket packet)

since there's a constraint on generic one, isn't it exactly the same? If not, what is the point difference here and what are the advantages of using generic one with constraint over a simle one?

Thanks!

J. Doe
  • 905
  • 1
  • 10
  • 23

1 Answers1

3

What is the point difference here and what are the advantages of using generic one with constraint over a simple one?

With generics, multiple constraints can be specified:

private void Send<T>(T packet) where T : IPacket, IFoo {
}
...

private void Send<T>(T packet) where T : IPacket, new() {
  var t1 = new T();
  var t2 = default(T);
}

There is also a small performance win when you use generics because direct calls tend to be faster than those made via interfaces.

Community
  • 1
  • 1
Alex Booker
  • 10,487
  • 1
  • 24
  • 34
  • Are you claiming that you have have both of those methods in the same class or that you can add additional constraints that you can't with just parameter types? In either case I think it changes the premise of the question. – D Stanley May 24 '16 at 18:34
  • No I am not. The `...` is supposed to be a delimiter between isolated snippets. – Alex Booker May 24 '16 at 18:39
  • Thank you @AlexBooker :) – J. Doe May 25 '16 at 07:46