7

Is there any major difference between using

 public TValue SomeFunctionA<TValue>(BaseClass<TValue> bc)

over

 public TValue SomeFunctionB<TValue, TBaseClass>(TBaseClass bc)
      where TBaseClass : BaseClass<TValue>

I've done some testing, and I can't seem to find any difference. All derived classes behave as they should (override something, new something, etc.).

What about if 'TValue' is known, such as (besides now you can use operators):

 public int SomeFunctionAInt(BaseClass<int> bc)

and

 public int SomeFunctionBInt<TBaseClass>(TBaseClass bc)
      where TBaseClass : BaseClass<int>

1 Answer 1

3

In this case there is no difference. Generics are used to flow type information. As soon as you want to call other code, or return a value and that value must be statically typed to be the same as the input parameter bc, you need generics.

For example, the two functions below output the same thing, but the 2nd preserves type information:

object PrintAndReturn1(object obj) { Console.WriteLine(obj); return obj; }
T PrintAndReturn2<T>(T obj) { Console.WriteLine(obj); return obj; }

Generics come into play when you want to preserve type information. If you only ever consume a value and not pass it around, inheritance is enough.

You say you found no difference during testing. This makes sense because the JIT erases the generic type information (mostly). The JITed code will look very similar for both variants. Virtual calls on references of a generic type are implemented the same way as non-generic v-calls. (Note, that this goes for reference types only. All ref types share one JITed code body.)

1
  • 1
    Technically, your two functions will act differently if obj is a struct. PrintAndReturn1 will either box the value on the stack onto the heap or - if the passed value is already on the heap due to being in a reference type of some kind - point to it. PrintAndReturn2 would always make a shallow copy of the passed struct and return another shallow copy of the paramter.
    – Tory
    Dec 27, 2013 at 16:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.