C# 2.0 Features: Property Accessor Accessibility Modifiers

C# 2.0 supports access modifiers for property accessor, which means now you can set access levels to get and set accessors of a property. For example, I can write a property something like this:

public string LoginName
{
get { return loginName; }
protected set { loginName = value; }
}

So now I can set LoginName property from any class derived from the class that has this property but I won't be able to set this property from other classes. This feature was not supported in previous version of C#.

I create a class called ABaseClass, which has LoginName property:

class ABaseClass
{
/// <summary>
/// Property Access Modifiers
/// </summary>
private string loginName;
/// <summary>
/// Login Name
/// </summary>
public string LoginName
{
get { return loginName; }
protected set { loginName = value; }
}
}

Now I create a new class, which is derived from ABaseClass and in this class I set set LoginName property.

class ADerivedClass : ABaseClass
{
public void SetPrivateProperty()
{
base.LoginName = "mcb";
}
}

If I try to set the property value from other classes, I get the following error:

PropAccessModImg1.gif

Up Next
    Ebook Download
    View all
    Learn
    View all