Alternative assignment of fields in constructor for struct / class

Just wanted to point out another way how to assign fields of classes / structs in the constructor. Ben called the parameters of the constructor aTime, aPos, aRot. Instead you can use the this reference so you do not need to have them have a different name than your fields:

public struct MyKeyFrame {

    public float frameTime;
    public Vector3 position;
    public Quaternion rotation;

    public MyKeyFrame(float frameTime, Vector3 position, Quaternion rotation)
    {
        this.frameTime = frameTime;
        this.position = position;
        this.rotation = rotation;
    }
}

Yup, though this highlights one of the key reasons for having alternative approaches to variable names in most languages, in C# specifically for example:

public float MyFloat;
private float _myFloat;

public void UpdateFloat(float myFloat)
{
    if (myFloat != MyFloat)
    {
        _myFloat = myFloat;
    }
}

:smiley:

1 Like

My float… just sunk! :smiley:

Enjoyed reading this Chris, nice example of naming conventions! :slight_smile:

Thanks Rob, its how I used to teach it to our juniors, always seemed to work :slight_smile:

1 Like

Privacy & Terms