PositiveGuy
PositiveGuy

Reputation: 47743

Alternative to private setters in Automatic properties

If you're not supposed to use private setters for automatic properties (bad practice) then how can I set it privately from within the class and still expose it with just a get to the public? (lets say I want to set it at the constructor level but still allow it to be public by get)?

example class:

public class Car
{
    //set the property via constructor
    public SomeClass(LicensePlate license)
    {
         License = license
    }

    public LicensePlate License{get; private set;} // bad practice
}

Upvotes: 0

Views: 319

Answers (1)

e_ne
e_ne

Reputation: 8459

You convert the property to one with a backing field and no setter.

public class Car
{
    LicensePlate _license;

    public Car(LicensePlate license)
    {
        _license = license;
    }

    public LicensePlate License
    {
        get { return _license; }
    }
}

Upvotes: 4

Related Questions