views:

635

answers:

5

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

+15  A: 

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

M4N
+1. As an aside, you can have private extension methods; there's a nice article on this at http://odetocode.com/Blogs/scott/archive/2009/10/05/private-extension-methods.aspx Extension methods can also access private static members of their static utility class.
TrueWill
Even though this is tagged as C#, this applies to any of the .NET languages which provide support for extension methods.
Scott Dorman
@TrueWill - but since they must be static, non-nested, non-generic types, they can't really have private access to any *object's* variables. `internal` access, sure - but not `private`.
Marc Gravell
@Marc - You are 100% correct. Thanks for the clarification.
TrueWill
+2  A: 

No, unless you give some kind of access to them through public properties or a proxy pattern.

Yuriy Faktorovich
+3  A: 

No:

public class Foo
{
    private string bar;
}

public static class FooExtensions
{
    public static void Test(this Foo foo)
    {
        // Compile error here: Foo.bar is inaccessible due to its protection level  
        var bar = foo.bar;
    }
}
Darin Dimitrov
A: 

An extension method is essentially a static method so all you have access to are the public members of the instance on which the extension method is invoked on

Abhijeet Patel
A: 

Look at this example

http://www.codeproject.com/Articles/80343/Accessing-private-members.aspx

ASAF