Search code examples
c#getsetencapsulationshorthand

Shorthand Accessors and Mutators


I am learning C#, and am learning about making fields private to the class, and using Getters and Setters to expose Methods instead of field values.

Are the get; set; in Method 1 and Method 2 equivalent? e.g. is one a shorthand of the other?

class Student
{
    // Instance fields
    private string name;
    private int mark;

    // Method 1
    public string Name { get; set; }

    // Method 2
    public int Mark
    {
        get { return mark; }
        set { mark = value; }
    }
}

Finally, would Method 2 be used when you want to for example perform a calculation before getting or setting a value? e.g. converting value to a percentage or perform validation? e.g.

class Student
{
    // Instance fields
    private string name;
    private double mark;
    private int maxMark = 50;

    // Method 1
    public string Name { get; set; }

    // Method 2
    public double Mark
    {
        get { return mark; }
        set { if ( mark <= maxMark ) mark = value / maxMark * 100; }
    }
}

Solution

  • Yes, Method 1 is a shortcut to Method 2. I suggest using Method 1 by default. When you need more functionality, use Method 2. You can also specify different access modifiers for get and set.