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.
User user = new User(); // this is my object!
user.Name = "Anthony Pegram"; // this is my name!
User otherUser = new User(); // this is your object!
otherUser.Name = "Heisenburg"; // this is your name!
// my object is not your object
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 static keyword on the property.
class Foo
{
public static string Bar { get; set; }
}
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.
Foo.Bar = "Blah"; // no instance necessary
string data = Foo.Bar;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With