C# Property Access Modifier

C# property can be assigned an access modifier (public, private, protected, or internal) to control the accessibility of that property against an external caller. Prior to .NET 2.0, we could not declare a property with different access modifier for the accessor (get and set). This is somewhat limiting, considering that sometimes we want the set operation to be less public than the get operation. If you want to do that in C# 1.x, you have to do this (which is not pretty and defeats the purpose of Property syntax):

public string Name
{
    get
    {
        return name;
    }
}

internal string SetName(string name)
{
    this.name = name;
}

Luckily, the problem was recognized and addressed in C# 2.0 with the introduction of “Asymmetric Accessor Accessibility”. So now you can do this:

public string Name
{
    get
    {
        return name;
    }
    internal set
    {
        name = value;
    }
}

There are some restrictions for this, the most important ones being:

  • The accessor (get or set) access modifier must be more restrictive than the property access modifier.
  • Accessor modifier can only be defined when a property has both get and set accessors and the accessor modifier is only permitted on only one of the two accessors.

Just in case you’re not up to date.

About these ads

Posted on September 2, 2007, in Code Junky. Bookmark the permalink. 2 Comments.

  1. That a nice addition for in C# 2.0. I had been exploring the MSIL generated for the accessors and found there is nothing like protected or internal in the MSIL. protected is actually family and internal is assembly.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: