Let me just preface this by saying that I know this is probably a newbie quesion, I tried searching for it and I can't find a proper anwser for it (probbably asking it wrong).
So usually when I want to use another value outisde of its class, I just make it public and access it lik.
Yet often I see other code use private values in their class and then make separate functions for getting and setting the value like so:
private bool fooBar;
public void SetFooBar(bool boolean)
{
fooBar = boolean;
}
public bool GetFooBar()
{
return fooBar;
}
Excuse my ignorance but what exactly is the point of it? They both do essentially the same thing (by my newbie logic atleast). I know that private variables are useful in that it ensures you can't break the functionality of a program by modifying them elsewhere in the code, but you're modifying them elsewhere in the code anyway, so what gives? Why do I see people do this?
Because certain things (like WPF bindings) only work with properties, not fields
Because you may want to change how the value is retrieved/stored (not just in-memory) later
(Note that in C# you usually do this as a property, not methods, like public bool Foo {get; set;}
)
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