Asymmetric Accessor Accessibility in C# 2.0 came up in the Sarasota .NET Developer Group Meeting last night as well as a conversation I had this morning, so I thought it would be worth sharing.
C# 2.0 introduces a new concept, called Asymmetric Accessor Accessibility, which essentially means you can modify the visibility of either the get accessor or set accessor on a class property that has both a “getter” and “setter.”
This allows you to do something like below:
public class Customer
{
private int _customerID;
private string _firstname = string.Empty;
private string _lastname = string.Empty;
public int ID
{
get
{
return _customerID;
}
internal set
{
_customerID = value;
}
}
// ...
}
Here we have restricted the visibility of the set accessor to internal, which means only a class in the same assembly as Customer can set the ID of the Customer via the set accessor.
There are a few restrictions to this new asymmetric accessor accessibility feature in C# 2.0. The most relevent are:
1. You can only set a different visibility on 1 of the 2 accessors, not both. Trying to restrict visibility on both get and set to internal will give the following error:
“Cannot specify accessibility modifiers for both accessors of the property or indexer”
2. You cannot use the feature on properties that do not have BOTH a get and set accessor. Removing the get accessor from the example above will give you this lovely error:
“accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor”
3. The accessibility modifier used on a get or set accessor can only restrict visibility not increase it. Hence doing something like this:
public class Customer
{
private int _customerID;
private string _firstname = string.Empty;
private string _lastname = string.Empty;
protected int ID
{
get
{
return _customerID;
}
public set
{
_customerID = value;
}
}
// ...
}
would give you the following error because the property has a protected access modifier that is more restrictive than the public set accessor and not the other way arround:
“accessor must be more restrictive than the property or indexer“
I have yet to use the Asymmetric Accessor Accessibility Feature of C# 2.0, but it is good to know it is there. For more information on new language features in C# 2.0, you can always check out the C# Programming Guide on MSDN.
Source: David Hayden ( Florida .NET Developer )