If I create a new Class, and in this class I put a property like so:
public class CurrentDirectory
{
private string cd;
public string CurrentDirectory
{
get
{
return cd;
}
set
{
cd = value;
}
}
I then, at one point in my program, create a new instance of this class like so:
CurrentDirectory myCurrentDirectory = New CurrentDirectory();
I then set a value to CurrentDirectory like so:
myCurrentDirectory.CurrentDirectory = @"C:\MyFiles\Here";
Then, at another point in my program I create another instance of CurrentDirectory and ‘get’ the value of CurrentDirectory like so:
CurrentDirectory myCurrentDirectory1 = new CurrentDirectory();
string putFilesHere = myCurrentDirectory1.CurrentDirectory;
Will this return the value I set earlier or do I need to ‘get’ and ‘set’ my value within the same instance?
Thanks
No, this does not hold values in this way, no more than setting one user’s name to “Heisenburg” affects my name of “Anthony Pegram”. Each instance of the class is a different object, and instance properties and members of one instance do not carry over to other instances.
If you need to share properties to where some other place sees the same value you set elsewhere, you need to either share the instance, or make the data itself shared via the
statickeyword on the property.If using statics, the state becomes global, and is not tied to a particular instance. It, in fact, does not need an instance. You would simply access it via the class name directly, not via an object of that class.