Can C# extension methods access private variables?

Geo picture Geo · Oct 10, 2009 · Viewed 30.6k times · Source

Is it possible to access an object's private variables using an extension method?

Answer

M4N picture M4N · Oct 10, 2009

No. You can do the same in an extension method as in a "normal" static method in some utility class.

So this extension method

public static void SomeMethod(this string s)
{
    // do something with 's'
}

is equivalent to some static helper method like this (at least regarding what you can access):

public static void SomeStringMethod(string s)
{
    // do something with 's'
}

(Of course you could use some reflection in either method to access private members. But I guess that's not the point of this question.)