Search Unity

{get; set;} ??

Discussion in 'Scripting' started by sogdo, May 15, 2011.

  1. sogdo

    sogdo

    Joined:
    Mar 21, 2011
    Posts:
    44
    What does it mean or do when there is a bool with {get; set;}
    Code (csharp):
    1.  public bool blahVar {get; set;}
     
  2. jgodfrey

    jgodfrey

    Joined:
    Nov 14, 2009
    Posts:
    564
    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.
     
    undevable likes this.
  3. sogdo

    sogdo

    Joined:
    Mar 21, 2011
    Posts:
    44
    Ah I see, thank you
     
  4. Jessy

    Jessy

    Joined:
    Jun 7, 2007
    Posts:
    7,325
    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?
     
    Last edited: May 16, 2011
    Tonymotion likes this.
  5. jgodfrey

    jgodfrey

    Joined:
    Nov 14, 2009
    Posts:
    564
    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.
     
  6. Jessy

    Jessy

    Joined:
    Jun 7, 2007
    Posts:
    7,325
    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.
     
  7. Dreamora

    Dreamora

    Joined:
    Apr 5, 2008
    Posts:
    26,601
    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)
     
  8. KyleStaves

    KyleStaves

    Joined:
    Nov 4, 2009
    Posts:
    821
    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.
     
    Tonymotion likes this.
  9. badkenny

    badkenny

    Joined:
    Jun 7, 2012
    Posts:
    7
    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):
    1. public float travelingSpeed {get; private set;}
     
  10. CrazySi

    CrazySi

    Joined:
    Jun 23, 2011
    Posts:
    538
    Serialization.
     
  11. Jaimi

    Jaimi

    Joined:
    Jan 10, 2009
    Posts:
    6,208
    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.
     
  12. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,539
    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):
    1.  
    2. public class Foo
    3. {
    4.     public Vector3 Loc = Vector3.zero;
    5.     public Vector3 Location
    6.     {
    7.         get { return Loc; }
    8.         set { Loc = value; }
    9.     }
    10. }
    11.  
    Now consider the following use:
    Code (csharp):
    1.  
    2. var obj = new Foo();
    3. obj.Loc.X += 5;//works
    4. obj.Location.X += 2;//error, won't compile, "can not modify the return value because it is not a variable"
    5.  
    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.
     
    Last edited: Oct 11, 2012
  13. LouisHong

    LouisHong

    Joined:
    Nov 11, 2014
    Posts:
    69
    Boom, that's one word that explains it all for me, thank you
     
  14. sdclark79

    sdclark79

    Joined:
    Feb 6, 2017
    Posts:
    21
    As a 2017 update to this long-dead thread, this:
    Code (CSharp):
    1. public bool blahVar {get; set;}
    is shorthand for writing this:
    Code (CSharp):
    1. private bool blahvar;
    2.  
    3. public bool blahVar{
    4.         get{
    5.             return blahvar;
    6.         }
    7.  
    8.         set{
    9.             blahvar = value;
    10.         }
    11.     }
    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):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class myPlayer {
    6.  
    7.     private int experience = 100;
    8.  
    9.     public int Experience{
    10.         get{
    11.             return experience;
    12.         }
    13.  
    14.         set{
    15.             experience = value;
    16.         }
    17.     }
    18.  
    19. }
    You can Get and Set that value from another script:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. //This script that calls the Get/Set variable has to be in the scene
    6. public class myGame : MonoBehaviour {
    7.     //This gives a reference to the myPlayer script
    8.     myPlayer newmyPlayer = new myPlayer();
    9.  
    10.     void Start(){
    11.         //This tests getting the Experience field from the script
    12.         int x  = newmyPlayer.Experience;
    13.         Debug.Log(x);
    14.     }
    15.  
    16.     void Update(){
    17.         //This tests setting the experience field
    18.         if(Input.GetKeyDown(KeyCode.Return)){
    19.             newmyPlayer.Experience = newmyPlayer.Experience - 10;
    20.         }
    21.         //And this tests if we can get the newly set experience field
    22.         if(Input.GetKeyDown(KeyCode.M)){
    23.             Debug.Log (newmyPlayer.Experience);
    24.         }
    25.     }
    26.  
    27. }
    Hope that helps!
     
  15. Deleted User

    Deleted User

    Guest

    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):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Player
    6. {
    7.     private int experience = 342;
    8.     private int level = 1;
    9.  
    10.     public int Experience
    11.     {
    12.         get
    13.         {
    14.             return experience;
    15.         }
    16.  
    17.         set
    18.         {
    19.             experience = value;
    20.         }
    21.     }
    22.  
    23.     public int Level
    24.     {
    25.         get
    26.         {
    27.             return level;
    28.         }
    29.  
    30.         set
    31.         {
    32.             level = value;
    33.         }
    34.     }
    35. }
    36.  
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Game : MonoBehaviour
    6. {
    7.     private int x;
    8.     private int y;
    9.  
    10.     private Player myPlayer = new Player();
    11.  
    12.     private void Start()
    13.     {
    14.         x = myPlayer.Experience;
    15.         y = myPlayer.Level;
    16.  
    17.         Debug.Log(x);
    18.         Debug.Log(y);
    19.     }
    20.  
    21.     private void Update()
    22.     {
    23.         if (Input.GetKeyDown(KeyCode.Space))
    24.             x = x + 100;
    25.  
    26.         if (Input.GetKeyDown(KeyCode.Return))
    27.         {
    28.             Debug.Log(x);
    29.         }
    30.  
    31.         if (x >= 1000)
    32.         {
    33.             LevelUp();
    34.         }
    35.     }
    36.  
    37.     private void LevelUp()
    38.     {
    39.         y++;
    40.         x = x - 1000;
    41.  
    42.         Debug.Log(y);
    43.     }
    44. }
     
  16. ADNCG

    ADNCG

    Joined:
    Jun 9, 2014
    Posts:
    994
    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):
    1. return experience/100;
     
    Pr0x1d and Deleted User like this.