First, just to correct (or at least clarify your comments), static members can only be accessed through their class in C# (not so in VB which allows instance as well).
Secondly Matt, I would just like to show you another bit of code. Let me just say that the behaviour of what is happening is slightly confused because the Main method is located within the Class itself and so code within is able to "peek" at private members. This kind of breaks the encapsulation rule in a sense BUT it is obvious why it is doing it - and maybe future C# specifications should enforce entry points to be the only member of a class (open to debate), I however quite like this quirk.
If you see the code below you will see that all members of the class are accessible to Main(), however the public and private members *must* be accessed via and instance of the class and the static public and static private members *must* be accessed through the class itself and *cannot* be accessed through an instance.
Just before I show you the code listing though, I advise you not to get too hung up with this scenario and for a better illustration to see how it all works normally it is probably best to put your entry point in a completely separate class.
using System;
namespace Test
{
class Class1
{
public static string MATT = "public static Matt";
private static string Matt = "private static Matt";
private string matt = "private matt";
public string MatT = "public matt";
//private Class1(){} //to see what I mean remove comment and this instanciation of Class1 will still work within Main!
[STAThread]
static void Main()
{
{
// matt = "" //is inaccessible unless reference through instance
Class1 c = new Class1();
Console.WriteLine(c.matt); //is accessible through instance only from within this Main (cos it is private)
Console.WriteLine(c.MatT); //is accessible through instance (cos it is public)
Console.WriteLine(Matt); //is accessible through class only from within this Main (cos it is private)
Console.WriteLine(Matt); //is accessible through class (cos it is public)
Console.ReadLine();
}
}
}
}
--
--
Br,
Mark Broadbent
mcdba , mcse+i
=============
"Ken Allen" <
[email protected]> a écrit dans le message de -- but the Main() still could not since you declared it private.
-Ken
I disagree with this part.
Even thought matt is private, it does not matter wether or not main is static. You CAN access all member of the class form main method (static members, or instance members with a valid instance of course).
Fred