Joshua Enfield
Joshua Enfield

Reputation: 18278

Can extension methods access the "this" object?

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?

Upvotes: 3

Views: 1920

Answers (2)

TomTom
TomTom

Reputation: 62093

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.

Upvotes: 6

user541686
user541686

Reputation: 210352

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

Upvotes: 1

Related Questions