Search code examples
c#c#-4.0getter-setter

Use of private set property in C#


Can somebody explain the use of private access modifier with set property and default with get property in C# getter and setter methods? I am pretty new to the C# programming language.

Sample code:

public Status
{
    get { return my_status; }
    private set
    {
            if (value != my_status)
            {
                //something here
                my_status=value;
            }
    }
}

Solution

  • If you don't specify any access modifier for the get/set the property access modifier will be used. You can specify a more restrictive access modifier for get or set.

    In your example, since Status is public but has a private set, the property will be readable from anywhere but assignable only from within the declaring class.