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?
Asked
Active
Viewed 1,716 times
2 Answers
6
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
namespace ExtensionMethods
{
public static class MyExtensions
{
public static int WordCount(this String str)
{
return str.Split(new char[] { ' ', '.', '?' },
StringSplitOptions.RemoveEmptyEntries).Length;
}
}
}
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.

TomTom
- 61,059
- 10
- 88
- 148
1
No; you have to use the actual name of the argument.

user541686
- 205,094
- 128
- 528
- 886
-
Name of the *parameter* rather than argument, but otherwise yes. – Jon Skeet Apr 06 '11 at 05:26
-
@Jon Skeet: [Or just *parameter*?](http://stackoverflow.com/questions/1663705/difference-between-arguments-parameters-in-c/1663724#1663724) – BoltClock Apr 06 '11 at 05:30
-
@Jon: Way to be picky :P but yes, "argument" is not the correct term. I stand corrected. – user541686 Apr 06 '11 at 05:33