Search code examples
c#privateencapsulationpublic

Why would I use auto-implementation over encapsulation?


private int someInt;

public int GetSomeInt()
{
    return someInt;
}

When would I use the above code over the below code?

public int SomeInt { get; set; }

I've been told to always encapsulate all variables rather than declaring them as public, and auto-implementation seems to be doing just that.

Doesn't this nullify the purpose of encapsulation as the field is declared public?


Solution

  • When would I use the above code over the below code?

    When you are paid by the parenthesis? :-)

    Remember that the code

    public int SomeInt { get; set; }
    

    is shorthand for the equivalent of

    private int someInt;
    
    public int SomeInt
    {
       get { return someInt; }
       set { someInt = value; }
    }
    

    So any logic you could imagine putting in your GetSomeInt method can also be put in the 'getter' (or 'setter') for the SomeInt property.

    Where possible, you should use the public int SomeInt { get; set; } syntax since it immediately alerts the reader that what you have is a simple property that can be set or accessed without any further logic to be understood.

    Where the get or set logic is more complex the longer form of the property definition can be used.

    Notwithstanding my facetious remark about parentheses, the Framework Design Guidelines for Property Design suggest that

    If a getter can throw an exception, it should probably be redesigned to be a method. Notice that this rule does not apply to indexers, where we do expect exceptions as a result of validating the arguments.

    So that would be one example of a situation where you might implement GetSomeInt rather than a SomeInt property getter.