Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Getters and Setters in Unity

Tags:

c#

unity3d

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.

like image 795
Tobias Johansson Avatar asked Dec 20 '22 15:12

Tobias Johansson


1 Answers

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.

like image 96
John Källén Avatar answered Jan 07 '23 08:01

John Källén