If you take a look at the documentation for Extension Methods
(
http://msdn.microsoft.com/en-us/library/bb383977.aspx), there is a
statement there that says:
"In fact, extension methods cannot access private variables in the type they
are extending"
So could this be perhaps one of the reasons why extension methods are not
allowed in instance classes? I am thinking that if such thing was allowed,
you could do something like the snippet below:
--------------------------
class Foobar
{
private int privateVar;
public static void DoIt(this Foobar f)
{
f.privateVar = 123;
}
}
--------------------------
In this snippet, you can see that the extension methods *would* have access
to private methods and this would violate what is stated on the
documentation.
Of course, I realize that doing something similar to what I did on my
example is pretty pointless and stupid but that is beside the point. All I
really wanted to demonstrate is how the rule of extension methods not having
access to private member can be violated if extension methods where allowed
to be declared in instance classes.
Any thoughts?
Thanks.
"Family Tree Mike" <Fa************@ThisOldHouse.comwrote in message
news:u8****************@TK2MSFTNGP05.phx.gbl...
>I was surprised this was the case and tried it. The only thing I can think
of is that in a non-static class, "this" has a certain meaning that is
unnecessary in a static class. I suppose there could be confusion
regarding "this" in the method declaration within a non-static class at
compile time.
"Rene" <a@b.comwrote in message
news:%2******************@TK2MSFTNGP06.phx.gbl...
>Hi,
I was wondering if anyone could tell me why extension methods must be
declared on static classes. I mean, why not allowing them to be declared
as static methods in regular instance classes?
In case you are wondering, I am only curious to find out the reason for
this limitation. I don't really have a need to declare extension method
on non static classes. I am just curious.
Thanks