3

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?

Joshua Enfield
  • 17,642
  • 10
  • 51
  • 98

2 Answers2

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