I had a Problem lastly while i was working in Unity I had a public Variable hidden in the Editor this caused me some Proplems which i reported as Bug because for me it looked like one
I did it like this:
public bool Variable_1 = true;
The Unity Support member than said to me that nothing is wrong with my Code but i should do it like this because this would be prefered:
private bool Variable_1{
get
{
return this.Variable_1;
}
set
{
this.Variable_1 = value;
}
}
public void Set_Variable_1(bool bool){
this.Variable_1 = bool;
}
I wanted to make it public because i want to access it from a other class
So my Question is why would some one use the second Example Code over the first one. What is the Advantage of that? Because in my eyes the first example is much simpler and takes less lines [Edit] 21.7.17: I understand that getter and setter Methods are much more flexible but in this case it won't be needed.
Thanks for taking the Time and Reading this Post. Have a nice Day and keep Coding
[Edit] 21.7.17:
Also i like to point out that i teached Programming myself so i didn't look into set and get till now. I tried to understand the example from this site www.dotnetperls.com/property which is ruffly the same as my Example now. I don't know how good this site is but i understood it best there
There´s indeed no reason to make the field a private property and set its value by a public setter-method. Instead you should create a property with a public getter and setter.
public bool Variable_1 { get; set; }
Apart from this none of your two solutions is a good idea, a public field enables anyone to set the value to any value, making it impossible to perform any validation on the new value. This of course also applies to an auto-implemented property like the above. However if you decide some time to do implement some validation any existing client-code won´t be affected as the public API stays the same. Doing this with a public field on the other side would be a breaking change, as you´d replace a field by a property.
The second one however is overcomplicated and does not provide any advantage.