Public/private

Interesting introduction to the getters / setters. For clarity purposes, am I right in saying this is more a teaching case implementation rather than a real world one?

I ask because the code basically makes facingLeft a public bool (as I think you mention), which is a generally bad thing. I have generally used getters before, but starting to use public bool x { get; private set }. What are the pro’s / cons of each approach?

This is very much used everywhere in the real world.

Making a property public is not a bad thing. Making the wrong property public could be. Making the setter private makes it read-only and only the containing class can alter its value. If only this class should change the value, then it should be private. If other classes may change it, it should be public. The danger comes in when you have a public setter when you don’t want one and somewhere, some other developer doesn’t know this and alters the value from another class.

Getter/Setter methods and properties are pretty much the same thing. Property getters and setters just make it easier to code and using any variant is a matter of preference, I suppose

// This
private string property;
public void SetProperty(string value)
{
    property = value;
}
public string GetProperty()
{
    return property;
}

// is the same as this property
private string property;
public string Property
{
    get
    {
        return property;
    }
    set
    {
        property = value;
    }
}

// and this auto-property
public string Property { get; set; }
1 Like

Perfect. Thanks.

Privacy & Terms