What does it mean or do when there is a bool with {get; set;} Code (csharp): public bool blahVar {get; set;}
That's a C# auto-implemented property. It's a short-hand way of creating standard setters and getters without having to code them by hand. It was made available in C# 3.0 I think. So, using that, you can both set and get the value of the blahVar property without having to manually code the backing fields, though the automated version provides only simple, default behavior.
I know about automatic properties, but don't quite understand the point yet. This answer suggests that it's so that if you want to make a more complex getter and setter, you won't break code. I assume that's about camelCase versus PascalCase?
Jessy, Your link seems to lead to a general Google search results page, so I'm not sure which link you're referencing. Anyway, regarding auto-implemented properties - I just view it as a "strictly for the sake of convenience" advancement to the C# language. After all, it accomplishes nothing that couldn't be done prior to C# 3.0. It's just a high-use situation (private fields with public properties) that now requires (quite a bit) less code for the standard case.
Sorry; I updated the link. I just don't see a point to a public property that functions exactly the same as a public variable.
There is only one point and thats code consistency as in "always properties to access member variables". Otherwise a get,set with no custom implementation isn't really offering much (a only get naturally is offering a lot)
Strictly speaking there really is no point, at least not in Unity (from what I understand certain .Net mechanics - especially web related - regard public variables as a bug while recognizing properties). The major reason it's considered best practice really boils down to encapsulation. A public variable exposes the actual implementation of your class, where as a property (even a simple get; set; one) does not. Properly encapsulated code is just plain easier to maintain in the long run; if your implementation changes, you do not need to make any changes to other classes - you can simply adjust your properties as needed. Working with a large team/on a large project it also makes life much easier if you eventually do change the implementation and wish to change the property as well. You can easily depreciate a property out over time, with a public variable this really isn't an option (without getting really convoluted). Heck, I even encapsulate my public variables in situations where I need it to be public to expose it in the editor (and it's too simple/I'm too lazy to justify a custom editor). If I ever need to validate that information, or perform a task when the value changes it makes life so much easier. The long term benefits outweigh the two seconds it takes to set up a property by a huge amount.
Don't forget you can tack on access modifiers to the get and set of the property, just as you could if you weren't going the automagic route. What I've used them for is when I want to have public read access and private write access, like so: Code (csharp): public float travelingSpeed {get; private set;}
This is by far the best use of automatic properties, In my opinion. Saves a bunch of typing too. Properties hide implementation details. Automatic properties hide the backing variables, so you don't wind up accidentally using them in the class when you shouldn't.
Also when implementing interfaces. Interfaces doesn't define fields/vars, it only does properties and methods. Also a property and a field look completely different when reflected. And probably most importantly, value types are returned by reference in a field, but by value in a property. Example: Consider the following class... Code (csharp): public class Foo { public Vector3 Loc = Vector3.zero; public Vector3 Location { get { return Loc; } set { Loc = value; } } } Now consider the following use: Code (csharp): var obj = new Foo(); obj.Loc.X += 5;//works obj.Location.X += 2;//error, won't compile, "can not modify the return value because it is not a variable" Now in this last issue, you may say "well I would stick to fields/vars then because obviously properties are limited and crap by comparison"... but the thing is, I may actually want that. That's the encapsulation bit... I don't want people getting direct references to my fields (think 'ref' and 'out' in function parameters). In the end, a property is technically a function. They act more like functions then they do like fields (think how java doesn't have properties because they say you can just get the same functionality with a function). And this is just short-hand syntax sugar to make implementing said properties easier to meet the design requirements of your code... in software like I write for work (business software), this is VERY important.
As a 2017 update to this long-dead thread, this: Code (CSharp): public bool blahVar {get; set;} is shorthand for writing this: Code (CSharp): private bool blahvar; public bool blahVar{ get{ return blahvar; } set{ blahvar = value; } } The reason for using it is that you can set Read/Write on the "blahvar" bool. If you leave out the Get, it's write only. If you leave out the Set, it's read only. If you have this code in a file: Code (CSharp): using System.Collections; using System.Collections.Generic; using UnityEngine; public class myPlayer { private int experience = 100; public int Experience{ get{ return experience; } set{ experience = value; } } } You can Get and Set that value from another script: Code (CSharp): using System.Collections; using System.Collections.Generic; using UnityEngine; //This script that calls the Get/Set variable has to be in the scene public class myGame : MonoBehaviour { //This gives a reference to the myPlayer script myPlayer newmyPlayer = new myPlayer(); void Start(){ //This tests getting the Experience field from the script int x = newmyPlayer.Experience; Debug.Log(x); } void Update(){ //This tests setting the experience field if(Input.GetKeyDown(KeyCode.Return)){ newmyPlayer.Experience = newmyPlayer.Experience - 10; } //And this tests if we can get the newly set experience field if(Input.GetKeyDown(KeyCode.M)){ Debug.Log (newmyPlayer.Experience); } } } Hope that helps!
Hi! Yes, it did help! I'm happy I've found this post of yours because I was lost trying to understand how to use properties. Now things a clearer, thanks to you. Using your examples, I managed to use two properties to monitor the level of the player; it took me quite some time but they work. At the same time, if you, or someone else more versed than me in those things, could take a look at them and give me some advice, I would be happy. I also tried using self-declared properties in the player class and things work perfectly. But, in the tutorial about properties on this site, it is said that we can use code within the properties. I'd like to know more about that; what kind of code? Thank you for your attention! Here are my scripts: Code (CSharp): using System.Collections; using System.Collections.Generic; using UnityEngine; public class Player { private int experience = 342; private int level = 1; public int Experience { get { return experience; } set { experience = value; } } public int Level { get { return level; } set { level = value; } } } Code (CSharp): using System.Collections; using System.Collections.Generic; using UnityEngine; public class Game : MonoBehaviour { private int x; private int y; private Player myPlayer = new Player(); private void Start() { x = myPlayer.Experience; y = myPlayer.Level; Debug.Log(x); Debug.Log(y); } private void Update() { if (Input.GetKeyDown(KeyCode.Space)) x = x + 100; if (Input.GetKeyDown(KeyCode.Return)) { Debug.Log(x); } if (x >= 1000) { LevelUp(); } } private void LevelUp() { y++; x = x - 1000; Debug.Log(y); } }
You can throw logic inside your get/set. e.g. Say you level up once every 100 experience points, you could entirely remove your "level" variable. Your could create the Level property with a get accessor only and the accessor could return the following instead of a level variable. Code (CSharp): return experience/100;