0

Why do you use Private fields in a class if an outside class can change the private fields using get and set properties?

2
Contributors
1
Reply
25
Views
3 Years
Discussion Span
Last Post by deceptikon
3

Because if the fields are public, users of the class have unrestricted access to them. Exposing fields through properties introduces a controlled interface. Presumably your question is about this:

class Foo
{
    private int _bar;

    public int Bar
    {
        get { return _bar; }
        set { _bar = value; }
    }
}

This is indeed not much better than making _bar public. The only benefit here is that you have the option of controlling access in the future without changing the public interface. For example, let's say that you later decide Bar can only have a range of [1,10):

class Foo
{
    private int _bar;

    public int Bar
    {
        get { return _bar; }
        set
        {
            if (value > 0 && value < 10)
            {
                _bar = value;
            }
        }
    }
}

This cannot be done if _bar was public originally.

General best practice is for private fields to be used for anything that only the class has access to, public fields should not be used without very good reason, and public properties should be used to expose a controlled interface to private fields if needed.

Edited by deceptikon

Votes + Comments
cool one...
Beat me to it
easy to understand with a clear example!
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.