I have another question about this with getters and setters. Now that I started working with c# getters and setters as I understood them. The problem I see is that why should I make public variable that looks like this:
// Variable
private int _iRandomNumber
// Getter and setter
public int iRandomNumber
{
get { return _iRandomNumber; }
set { _iRandomNumber = value; }
}
I don't see the point of that since what different would it then be to just make the variable public since it's anyway got the get and set in the same bracket?
However if I do like this:
// Variable
private int _iRandomNumber
// Getter and setter
public int GetiRandomNumber { get { return _iRandomNumber; } }
public int SetiRandomNumber { set { _iRandomNumber = value; } }
Then when I try to use my SetiRandomNumber by itself Unity complier complains that I cannot use my SetProperty since I do not have a GET property inside my SET. Should I really have to make it like the first example I wrote because as I wrote then what's the point of Getters and Setters in c#?
Or should I instead move away from them, like I asked from the beginning and make functions for each Get and Set like in c++ so I can actually use them by themself?
Sorry for making this a new question, however it was not possible to add this as a comment in my previous question since it was to long.
Properties allow you to fire events when values are set, for instance:
public string Name {
get { return name; }
set {
name = value;
var eh = NameChanged; // avoid race condition.
if (eh != null)
eh(this, EventArgs.Empty);
}
}
private string name;
public event EventHandler NameChanged;
An added bonus is that you can track when your property gets set or read by putting breakpoints in the getter/setter with your debugger or diagnostic print statements.
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