Is there any noticeable difference between using an abstract class as a parameter to a method and a general parameter limited to the specified abstract class?

Is there any significant difference between use

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

above

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

I did some testing and I can not find any difference. All derived classes behave as they should (redefine something, new, etc.).

How about whether "TValue" is known, for example (you can also use operators now):

  public int SomeFunctionAInt(BaseClass<int> bc) 

and

  public int SomeFunctionBInt<TBaseClass>(TBaseClass bc) where TBaseClass : BaseClass<int> 
+7
generics c # abstract-class
source share
1 answer

In this case, there is no difference. Generics are used for stream type information. As soon as you want to call another code or return a value, and that value should be statically printed in the same way as the input parameter bc , you need generics.

For example, the two functions below output the same thing, but the second saves information like:

 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 save type information. If you only ever consume a value and don't skip it, inheritance is enough.

You say you did not find a difference during testing. This makes sense, as JIT erases information about the generic type (mostly). JITed code will be very similar to both options. Virtual calls to links to a common type are implemented in the same way as non-shared v-calls. (Note that this applies only to reference types. All link types have the same JITed code type.)

+3
source share

All Articles