0

Suppose I have the following code:

public class BaseClass { }
public class DerivedClass : BaseClass { }

public void GenericMethod<T>(T input) where T : BaseClass
{
 //code
}

public void NormalMethod(BaseClass input)
{
 //code
}

My question is what is the difference between the two methods? Is there any advantages or disadvantages to either method, and why?

Fabjan
  • 13,506
  • 4
  • 25
  • 52
Dan Horton
  • 105
  • 1
  • 5
  • In that particular scenario there really isn't any point in using a generic. Using the base class would be fine. Though there could be something in `code` that would warrant this – Liam May 30 '18 at 10:21
  • 4
    There is no difference in this case, you have found a perfect way to do the same things 2 different ways – TheGeneral May 30 '18 at 10:21
  • 1
    Possible duplicate of [What is cool about generics, why use them?](https://stackoverflow.com/questions/77632/what-is-cool-about-generics-why-use-them) – Liam May 30 '18 at 10:22
  • 3
    Contrast them with methods in a fluent API where the methods *return their input* after their action. Consider what the return types are then and what that means for fluent APIs. – Damien_The_Unbeliever May 30 '18 at 10:22
  • Also [When is it Appropriate to use Generics Versus Inheritance?](https://stackoverflow.com/questions/799369/when-is-it-appropriate-to-use-generics-versus-inheritance) – Liam May 30 '18 at 10:23

2 Answers2

4

What is the difference between the two methods?

Basically none.

Is there any advantages or disadvantages to either method?

At best there is a slight (compile-time) performance improvement when you use the non-generic version, since that doesn't need a specific version of the method to be compiled. Otherwise, there is nothing significant I can think of.

What could be a use case for using generics here:

  • When you would return T;
  • When T needs to derive from a class and an interface;
  • If your class uses a type argument, you could follow that over specifying the required type again.
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
1

It makes little sense to use generics in the code you show.

On the other hand, if you were to return T as opposed to BaseClass from that method, the caller can access T-specific members instead of only members declared on BaseClass (unless they cast the return value).

CodeCaster
  • 147,647
  • 23
  • 218
  • 272