Search code examples
c#extension-methods

Can C# extension methods access private variables?


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


Solution

  • 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.)