"Rajesh" <ra***************@gmail.comwrote in message
news:11**********************@p77g2000hsh.googlegr oups.com...
Based on my understanding static members do not have access to non-
static members.
That definition is inacurate.
Try
static members do not have access to non static members of the same
class without first creating an instance of the object and accessing the
nonstatic members via the instance.
take a look at this:
using System;
class Foo
{
private int x;
public Foo(int x){this.x = x;}
static void Main(string[] args)
{
Foo foo1 = new Foo(5);
Foo foo2 = new Foo(10);
Console.WriteLine(foo1.x);
Console.WriteLine(foo2.x);
}
}
---------------------
prints
5
10
---------------------
Since there is one x for every instance of Foo, you obviously can't
access x without knowing which foo it lives in.
It is not that "they" are attempting to restrict what static method
can/cannot do. It simply does not make sense for a static method to
access a nonstatic member without an instance of the object.
Now you may argue "Hey, what if it is a nonstatic Method? why can't I
access that?"
For instance (added to prior example)
public void Method1()
{
Console.WriteLine("x:{0}",x);
}
and
public void Method2()
{
Console.WriteLine("Hello from the inside of Foo");
}
Method1 makes no sense without an instance of Foo because it needs to
know the value of x
Method2 on the other hand knows nothing of the internal state of
Foo...so why can't I call it????
Because you didn't make it static!!!
There is absolutely no reason for Method2 to NOT be static.
Hopefully, my rambling will help clear this up a bit
Bill