Search code examples
c#oopencapsulation

Defining both Private Field and Property vs just Property


Following OOP's best practices, is it better to have this code:

class Car {

    private Driv driver;

    public Driv Driver {

        get { return driver; }

        set { driver = value; }
    }

}

Or this one?

class Car
{
    public Driv Driver { get; set; }
}

While the second version is shorter, I feel like I'm breaking the main premise of the Encapsulation concept:

EVERY class should keep its privates to itself.

Hope the answer is not too trivial.


Solution

  • There really is no difference. If no private variable is created by the user then the code will be generated automatically for the private field. However, if the user wishes to do additional logic in the getter or setter of the property then declaring a private field is necessary.