Just static, not public... scope?

  • Thread starter Thread starter christery
  • Start date Start date
C

christery

why? static works but not public on "a"...
First I thougt OK, but then... why not eaven private in the same
class...
Am I missing something about scope? Test.Program.a wont work either I
guess..
saw this as a q and now I got interested...

using System;
using System.Collections.Generic;
using System.Text;


namespace Test
{
class Program
{
static int[] a = { 2, 4, 6, 8 };


static void Main(string[] args)
{
for (int n = 0; n < 4; n++)
Console.WriteLine(a[n]);
Console.ReadKey();
}
}
}
 
It (a) can be declared "static public" or "static private". It has to be
declared static to be used in a static method. You cannot access properties
of an instance in a static method, as main is in this case.
 
why? static works but not public on "a"...

public and static are completely orthogonal concepts. "public" just
says which classes it's accessible to. "static" says that it's a member
related to the type as a whole rather than an individual instance of
the type.
First I thougt OK, but then... why not eaven private in the same
class...

What do you mean, exactly? Again, "private" and "static" are
orthogonal.
Am I missing something about scope? Test.Program.a wont work either I
guess..

No, Test.Program.a would work fine.
 
Now I saw the question you might have been refering to earlier. In that
question, the user had created an instance object in the static method. By
doing so in your main, you could access that objects copy of the a-array, if
a were declared public, but not static.

Family Tree Mike said:
It (a) can be declared "static public" or "static private". It has to be
declared static to be used in a static method. You cannot access properties
of an instance in a static method, as main is in this case.

why? static works but not public on "a"...
First I thougt OK, but then... why not eaven private in the same
class...
Am I missing something about scope? Test.Program.a wont work either I
guess..
saw this as a q and now I got interested...

using System;
using System.Collections.Generic;
using System.Text;


namespace Test
{
class Program
{
static int[] a = { 2, 4, 6, 8 };


static void Main(string[] args)
{
for (int n = 0; n < 4; n++)
Console.WriteLine(a[n]);
Console.ReadKey();
}
}
}
 
Back
Top