Information Technology Reference
In-Depth Information
Access Modifiers on Accessors
In this chapter, you've seen two types of function members that have get and set accessors:
properties and indexers. By default, both a member's accessors have the same access level as
the member itself. That is, if a property has an access level of public , then both its accessors
have that same access level. The same is true of indexers.
With C# 2.0, the accessors of a member can now, under certain conditions, have different
access levels. For example, in the following code, property Name has an access level of public ,
but the set accessor has an access level of protected .
class MyClass
{
private string _Name = "John Doe";
public string Name
{
get { return _Name; }
protected set { _Name = value; }
}
}
There are several restrictions on the access modifiers of accessors. The most important
ones are the following:
￿
An accessor can have an access modifier only if the member (property or indexer) has
both a get accessor and a set accessor.
￿
Although both accessors must be present, only one of them can have an access modifier.
￿
The access modifier of the accessor must be s trictly more restrictive than the access level
of the member.
Figure 6-19 shows the hierarchy of access levels. The access level of an accessor must be
strictly lower in the chart than the access level of the member.
For example, if a property has an access level of public , you can give any of the four lower
access levels on the chart to one of the accessors. But if the property has an access level of
protected , the only access modifier you can use on one of the accessors is private .
Search WWH ::




Custom Search