Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
319 views
Welcome To Ask or Share your Answers For Others

1 Answer

In general, the point is to separate implementation (the field) from API (the property).

Later on you can, should you wish, put logic, logging etc in the property without breaking either source or binary compatibility - but more importantly you're saying what your type is willing to do, rather than how it's going to do it.

I have an article giving more benefits of using properties instead of public fields.

In C# 3 you can make all of this a lot simpler with automatically implemented properties:

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

At that point you still have a public getter and a private setter, but the backing field (and property implementation) is generated for you behind the scenes. At any point you can change this to a "normal" fully-implemented property with a backing field, and you'll still have binary and source compatibility. (Compatibility of serialized objects is a different matter, mind you.)

Additionally, in this case you can't mirror the behaviour you want (the ability to read the value publicly but write it privately) with a field - you could have a readonly field, but then you could only write to it within the constructor. Personally I wish there were a similar shorthand for this:

public class Foo
{
    private readonly int id;
    public int Id { get { return id; } }

    ...
}

as I like immutable types, but that's a different matter.

In another different matter, it's generally not a good idea to expose arrays like this anyway - even though callers can't change which array WorkID refers to, they can change the contents of the array, which is probably not what you want.

In the example you've given you could get away without the property setter, just setting the field directly within the same class, but it would mean that if you ever wanted to add logging etc you'd have to find all those writes.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...