BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

C# Programming
.NET 2.0+

C# Decreased Property Accessor Visibility

In early versions of C#, properties could be declared with different scopes, such as public, private or internal. However, it was not possible to have different scopes for the get and set accessors. C# and the .NET framework 2.0 remove this limitation.

.NET 1.1 Property Declaration

When using C# with the .NET framework version 1.1 or earlier, you can define properties within classes. When declaring the property, you can specify a scope to be applied to both the get and set accessors. For example, to create a public property that can be read or written to from all external classes, you may use code as follows:

private string _name;

public string Name
{
    get { return _name; }
    set { _name = value; }
}

The above property is marked as public. This means that both accessors are automatically publicly available. If you want to limit the visibility of one of the accessors you must remove it altogether, creating either a read-only or write-only property. You can then add a method that provides access to the backing variable but with a less visible scope. For example, you may decide to make the property read-only and add a protected setter method as follows:

private string _name;

public string Name
{
    get { return _name; }
}

protected void SetName(string name)
{
    _name = name;
}

.NET 2.0 Decreased Accessor Visibility

With C# for the .NET framework version 2.0, the scope of the get and set accessors can be set individually, leading to more elegant code than that shown above. You create the property as usual, declaring a scope that would normally be applied to both accessors. You can then specify a less visible scope as a prefix for one of the accessors.

Only one accessor can be explicitly modified in this way, with the other using the scope of the property itself. You cannot specify a more visible scope for the accessor than the property. However, this is never a problem as you can just change the overall property to the more visible scope and limit the visibility of the other accessor.

To recreate the functionality of the previous example using only a property, you can use the following code:

private string _name;

public string Name
{
    get { return _name; }               // Public get
    protected set { _name = value; }    // Protected set
}
15 October 2008