No no no, you're mixing things up.... Static members of a class are members of a class you can access without an instance of that class. That is, they are shared by *all* instances. For example:
Code:
public class Whatever
{
private static int _counter = 0;
public static string GetStuff
{
get
{
_counter++;
return "Hello World " + _counter.ToString();
}
}
}
When you access this code like this:
Code:
Console.WriteLine (Whatever.GetStuf);
you'll get an ever increasing number each time you call this for the life time of the application.
Instance properties work on instances like this:
Code:
public class Whatever
{
private int _counter = 0;
public string GetStuff
{
get
{
_counter++;
return "Hello World " + _counter.ToString();
}
}
}
First, note how _counter is private, but accessible in the public GetStuff property. There's no need to make it public as GetStuff is now non-shared as well.
Calling code like this repeatedly:
Code:
for (i = 0; i < 10; i++)
{
Whatever whatever = new Whatever()
Console.WriteLine (Whatever.GetStuf);
}
will give you a new counter with each instance. Since the counter is instance based, it gets a value of 0 every time you create a new instance. Calling the GetStuff method repeatedly on a single instance does increase the counter.
You seem to missing a few very important basics of C#. May I suggest you get a good book like Wrox's Beginning C# or Professional C#? Learning this stuff just from trying things out and comparing them with C++ may get you in troubles later. Getting the basics from a good book will definitely help you in the long run.
Edit: My example may not be the best as I am using a read-only GetStuff property to return non-related data. Typically you would use this to hide a directly related "backing variable":
Quote:
private string _firstName = string.Empty;
public string FirstName
{
get
{
return _firstName;
}
set
{
_firstName = value;
}
}
|
For a discussion on why properties are useful, take a look here:
I have a question re: Oject Oriented Programming
Cheers,
Imar