Alex Rivera | Logout

Why use private members then use public properties to set them?

Asked 2010-01-25T13:00:09.577
22

Seen a few examples of code where this happens:

public class Foo
{
    string[] m_workID;
    public string[] WorkID
    {
        get
        {
            return m_workID;
        }
        private set
        {
            m_workID = value;
        }
    }
}

What's the point of this? Since the use m_workID unnescessary.

c#
Edit
Report

1 Answer

2

You can use C# 3.0 auto properties feature to save time typing:

public class Foo
{
    public string[] WorkID
    {
        get; private set;
    }
}

In addition properties gives you lot of advantages in comparison to fields:

  • properties can be virtual

  • properties hide implementation details (not all properties are just trivial variable accessors)

  • properties can contain validation and logging code and raise change events

  • interfaces cannot contains fields but properties

answered 2010-01-25T13:55:40.657

Your Answer