Re: Static vs Non-static

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance



"Rajesh" <rajesh.godavarthi@xxxxxxxxx> wrote in message
news:1176433402.791297.115100@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
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









.



Relevant Pages

  • Namespaces, or getting function foo.bar() declarations to work
    ... But a lot of it being grouping of what would otherwise be static members of the global namespace. ... with foo being a global variable. ... var foo=} ...
    (comp.lang.javascript)
  • Re: Static vs Non-static
    ... static members do not have access to non static members of the same ... Foo foo1 = new Foo; ... access a nonstatic member without an instance of the object. ... public void Method1() ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: novice advice on static use
    ... static one hitting an instance variable). ... public class Foo { ... resolved) i see that there are also static members and non public ... Could you please explain to me how the static method differs from others, ...
    (microsoft.public.dotnet.languages.csharp)
  • a very tricky question...
    ... In java in object only the nonstatic members are present & the static ... members donot reside in the object but we are accessing static members ...
    (comp.lang.java.gui)