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?

2 Answers 2

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.

1

No; you have to use the actual name of the argument.

3
  • Name of the parameter rather than argument, but otherwise yes.
    – Jon Skeet
    Apr 6, 2011 at 5:26
  • @Jon Skeet: Or just parameter?
    – BoltClock
    Apr 6, 2011 at 5:30
  • @Jon: Way to be picky :P but yes, "argument" is not the correct term. I stand corrected.
    – user541686
    Apr 6, 2011 at 5:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.