Search code examples
c#ooppropertiesfieldencapsulation

Should properties or fields be used internally in classes?


Typically you want to encapsulate data by providing getters and setters for your internal state. Example:

public class Person {
    private int age;
    public int Age { 
        get { return age; }
        set { age = value; }
    }
}

void Main() {
    Person alice = new Person();
    alice.Age = 20;
}

But let's say we then have this happen:

public class Person {
    private int age;
    public int Age { 
        get { return age; }
        set { age = value; }
    }

    public String WhatIsMyAge() {
        return "My age is: " + ???;
    }
}

void Main() {
    Person alice = new Person();
    alice.Age = 20;

    Console.WriteLine(alice.WhatIsMyAge());
}

Is it better to use the property, or the field, here? Does it matter? Since we are inside the native class, do we still care about encapsulating the internals?


Solution

  • In your example:

    private int age;
    public int Age { 
        get { return age; }
        set { age = value; }
    }
    

    You should use auto-implemented properties anyway.

    But if you'd have a backing field to provide additional logic in a property's getters or setters, such as validation, definitely use the property instead of the backing field: this makes it impossible for the type to assign values to properties which wouldn't pass validation when assigned through the property's setter.

    It should be safe to read the backing field, because getters shouldn't contain logic anyway. But for consistency, perform both read and write action through the property.