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

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.

commented: easy to understand with a clear example! +12
commented: Beat me to it +3
commented: cool one... +0
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.