0

I would like a technical difference between the following two Extension method declarations and when you would use one over the other:

public static void DoSomething(this MyClass theObject)

vs

public static void DoSomething<T>(this T theObject) where T : MyClass

For example, I know there is a difference when using this with an object of a class that inherits from MyClass class but I don't know why.

adinas
  • 4,150
  • 3
  • 37
  • 47
  • 1
    What difference do you think there is? – Zohar Peled Jul 04 '18 at 11:51
  • 1
    `typeof(MyClass)` and `typeof(T)` could be different if the parameter passed in **inherits** from `MyClass`, as an example. This does feel like a XY Problem - https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem - though, can you explain **why** you are asking the question? – mjwills Jul 04 '18 at 12:00
  • I am asking this question because of an answer I got to a previous question. making a change to use generics solved it. Here is the question https://stackoverflow.com/questions/51140212/use-dapper-contrib-with-inheritance – adinas Jul 04 '18 at 12:10
  • 1
    @adinas In this concrete example there is practically no difference other than the two method signatures being different. It probably only starts to matter when you use typeof(T) or you use T in the return type or you have multiple arguments that have to be of the same type T. – Freggar Jul 04 '18 at 12:23

1 Answers1

1

Assume this implementation:

public static List<T> DoSomething<T>(this T theObject) where T : MyClass
    => new List<T>();

Invoked as

MyChildClass x;  // MyChildClass : MyClass
var list = DoSomething(x); 
// list is an instance of List<MyChildClass>, instead of List<MyClass>
  • Use first (non-generic) when you don't need to know the "actual" (child) type.

  • Use second (generic) when you plan to use the "actual" type in further generic code.

I see it as a "smell" when someone designs a class/function as generic, even though it "doesn't need to be" generic = the base type would suffice. (Equivalent 'generic' impl is somewhat more difficult to read)

Vladi Pavelka
  • 916
  • 4
  • 12
  • Actually, this answer does make sense. I originally asked because of a previous question of mine (https://stackoverflow.com/questions/51140212/use-dapper-contrib-with-inheritance) and indeed my code there didn't work because it didn't know the "actual" (child) type until the method was changed to use – adinas Jul 04 '18 at 12:16
  • Clarification: The original answer there was a simple Extension Method and it did not solve the issue. – adinas Jul 04 '18 at 14:36