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
2009-10-10 16:05:47
+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
2009-10-10 16:49:12
Even though this is tagged as C#, this applies to any of the .NET languages which provide support for extension methods.
Scott Dorman
2009-10-10 17:25:37
@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
2009-10-10 22:31:18
@Marc - You are 100% correct. Thanks for the clarification.
TrueWill
2009-10-11 19:02:01
+2
A:
No, unless you give some kind of access to them through public properties or a proxy pattern.
Yuriy Faktorovich
2009-10-10 16:05:55
+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
2009-10-10 16:06:12
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
2009-10-10 17:09:03
A:
Look at this example
http://www.codeproject.com/Articles/80343/Accessing-private-members.aspx
ASAF
2010-07-01 02:01:46