On May 11, 8:36 am, Jordan Marr <jnm...@hotmail.comwrote:
Could you post a short but complete program we can compile showing the
above working?
Create a new console app and paste the following two .cs modules:
using System;
namespace Static_Bug
{
public class TestClass
{
private string m_SecondName;
public string SecondName
{
get { return m_SecondName; }
}
private int m_NameCount;
public int NameCount
{
get { return m_NameCount; }
}
public static TestClass Load()
{
TestClass testClass = new TestClass();
string[] names = {"bob", "john", "sam" };
testClass.m_SecondName = names[1];
testClass.m_NameCount = names.Length;
return testClass;
}
}
}
using System;
namespace Static_Bug
{
public class Startup
{
public static void Main()
{
TestClass testClass = TestClass.Load();
Console.WriteLine(string.Concat("2nd Name:\t",
testClass.SecondName));
Console.WriteLine(string.Concat("Name Count:\t",
testClass.NameCount));
Console.ReadLine();
}
}
}
Ahh. This is a different situation from that which you originally
posted.
In your original post, your static method referred to the instance
field all by itself, without a instance of the class. Your new code
instantiates the class and then refers to the instance field of that
instance.
There's nothing wrong with this. It's the same as saying:
public static ArrayList GetList()
{
ArrayList list = new ArrayList();
list.Add(5);
}
"Add" is an instance method, but since you made an instance of
ArrayList, and you're accessing ITS Add method, the compiler has
everything it needs: a reference to an instance method (or field, or
property) and an instance to which it belongs.
Now, one thing that may cause a bit of confusion with your example is
the subject of access. You declared the fields "private", and yet
something logically "outside" the instance (the static method) is able
to get at them. "private" access means that the fields are private to
the class, and the static method is part of the class, so it can get
at them, just as if you pass one instance of a class to another
instance, the instance method that receives another of its own class
as a parameter can get at private fields, properties, methods, and
events of both its own instance ("this.") and the instance that was
passed to it (e.g. "otherInstance.").
Similarly, a static method that is passed an instance of its
containing class, or instantiates its containing class (as your static
method does) can get at all of the private members of that instance,
since the static method also belongs to that same class.