Lets say I want to add an extension method to class B.
Can I get a reference to the instance of class B the extension method is invoked on by using the “this” reference inside my extension method?
Lets say I want to add an extension method to class B. Can I
Share
Yes and no. A short look at the documentation makes it VERY clear.
Per definition the first parameter of an extension method is the pointer to the object the method was called from / attached to, and it actually is a variable referenced by the this keyword but with it’s own name:
http://msdn.microsoft.com/en-us/library/bb383977.aspx
That makes it quite easy that there is a “this” there, named “str”. So, you can not use “this” (because that would point to the non-existing instance of the class the extension method is defined on), but you can declare your own replacement variable pointing to the object an extension method is attached to.