Quick question about initializing properties in c#…I have the following class with private variables and getters/setters:
using UnityEngine;
public class BikeUpgrades {
// Singleton access
private static readonly BikeUpgrades _instance = new BikeUpgrades();
#region Private variables
// Camera switch variables
private float _camSwitchDuration; // Duration in seconds of the time the 2d camera will last
private int _camSwitchCount; // Amounts of camera switch available to the player
#endregion
#region Constructor
public BikeUpgrades ()
{
if( _instance != null )
{
//Debug.LogWarning ("Cannot have two instances of singleton.");
return;
}
_camSwitchDuration = 2.0f;
_camSwitchCount = 1; // Does not call the "set{}" accessor
CamSwitchCount = 1; // Does call the "set{}" accessor
}
#endregion
#region Getters and Setters
public static BikeUpgrades Instance
{
get{ return _instance; }
}
public float CamSwitchDuration
{
get{ return _camSwitchDuration; }
set{ _camSwitchDuration = Mathf.Clamp( value, 2f, 10f ); }
}
public int CamSwitchCount
{
get{ return _camSwitchCount; }
set{ _camSwitchCount = Mathf.Clamp( value, 2, 10 ); }
}
#endregion
}
In the example above, when initializing _camSwitchCount = 1 in the constructor, the property CamSwitchCount returns 1 even tho the setter clamps the value between 2 and 10, because the setter isn’t being called.
When initializing CamSwitchCount = 1 in the constructor, the property CamSwitchCount returns 2 because the setter is being called and it works like planned.
My question is, should you initialize the private variables at all, or should you just initialize the property itself, since this seems to actually return the correct value?
I have been using properties for a while now, but never really delved into them too deep. Any guidance/tips/help would be very appreciated as far as good/bad practice and whether or not I should initialize a property in the class’s constructor or just initialize the private variable which the property returns?
Stephane