Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

Possible Duplicate:
When are Getters and Setters Justified

Why do we use get and set method in C#? And why do we use public and private method property?

For example:

public class Date
{
    private int month = 7;  
    public int Month
    {
        get
        {
            return month;
        }
        set
        {
            if ((value > 0) && (value < 13))
            {
                month = value;
            }
        }
    }
}
share|improve this question

marked as duplicate by Jim G., gbjbaanb, GlenH7, Walter, Mark Booth Jul 30 '12 at 10:52

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1  
This question is covered in depth here: csharpindepth.com/articles/chapter8/propertiesmatter.aspx –  Robert Harvey Jul 29 '12 at 7:07
1  
    
Those are two questions, not one. –  tdammers Jul 29 '12 at 15:00

1 Answer 1

Private set modifier is used to control the access to object's property value.

Public set modifier is directly accessing the object's property value.

When you have a closed Domain, as a rule of open/close principle, private set modifiers used to restrict direct access to modify the properties of the object.

Private setters were not available before .NET 2.0 Framework. This has meant that people have written separate SetXXX methods if they wanted a public getter but a more limited setter.

public class MyTest
{
    string someProperty;

    public string SomeProperty
    {
        get
        {
            return someProperty;
        }

        private set
        {
            someProperty = value;
        }
    }
}

The basic rules are that you can't specify an access modifier for both the getter and the setter, and you have to use the "extra" modifier to make access more restrictive than the rest of the property.

Your question example comes from MSDN article Using Properties (C# Programming Guide). Look at that again and it will clear up the things.

share|improve this answer
    
@imonbayazid, please have a look - meta.stackexchange.com/q/5234/187724 –  Yusubov Aug 3 '12 at 14:46

Not the answer you're looking for? Browse other questions tagged or ask your own question.