Getter vs Properties

Hi,

We have created a getter in the Experience component to acces the experiencePoints, can we use a property instead, and is there some kind of rule to prefer one from the other?

M. D.

There’s no hard and fast rule. The important part is that the property be publicly read only. I like to use public getters/private setters

private float experience;
public float Experience
{
     get => experience;
     private set
     {
          experience = value;
          onExperienceGained?.Invoke();
     }
}

A property is just ‘shorthand’ for writing getter and setter methods. ‘Under the hood’ it’s a little something like

// This (stealing Brian's sample)
private float experience;
public float Experience
{
    get => return _experience;
    private set
    {
        experience = value;
        onExperienceGained?.Invoke();
    }
}

// becomes
private float experience;
public float get_Experience() => experience;
private void set_Experience(float value)
{
    experience = value;
    onExperienceGained?.Invoke();
}

You thief, you!! :stuck_out_tongue:

There is one thing Properties can do that Getters and Setters can’t… Where the setter in a property is visible, you can use numeric values just like they were the type that they represent… for example:

public void GainExperience(float amount)
{
    Experience+=amount;
}

Now if Health calls GainExperience(100); the public method will use the property, and since the property is rigged to automatically call onExperienceGained, it’s a one and out procedure.

Thank bixario.

Thank you Brian.
I like much properties, but I thought they were less than getters and setters.
In fact you encourage me to use them :slight_smile:
M. D.