if i have a private property in a class, i'm wondering what technically the difference is between the following three scenarios (memory usage, usability, best practice, etc):
class testClass
{
private string myString1 = "hello";
private string myString2 { get { return "hello"; } }
private string myString3() { return "hello"; }
}
apart from obviously being able to set the value in myString1 and not in myString2 or myString3, i'm wondering more about how these differ in terms of efficiency?
I try to follow these rules where possible:
There are obviously going to be some situations where every last drop of performance is important, but in general I would attempt to follow best-practice until profiling tells you that optimisation is needed.
There's a good article here: Why Properties Matter
I personally prefer properties for things without side effects and explicit getter if something is calculate on the fly. Eg:
class User {
private string username;
public string Username {
get { return username; }
set { username = value; }
}
public Post GetLatestPost() {
// query the database or whatever you do here.
}
}
And a lot of the APIs I've seen seem to do it similar. Hope that helps.
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