Laman

Selasa, 17 Mei 2011

Get and Set Visibility of Class properties and Indexers in C# (C Sharp)

C# 2.0 introduction a new concept, called asymmetric Accessor Accesibility, which assentialy means you can modify the visibility of either  the get accesor or set accesor on class property thah has both a getter and setter. This allows you do something like bellow

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 set accsessor. There a few restrictions to this new asymmetric accessor accessibility feature om C# 2.0 the most relavant are :
1. You can only set a different visibility on 1 of the 2 accessor, not both. Trying to restrict visibility on both get and set to internal will give the following error:
"Cannot spesify accesibility modifiers for both accessors of the property or indexwe"
2. You cannot use the feature on preperties that do not have BOTH a get and ser accessor. removing the get accessor from the example above will give you this lovely error:
"Accessibility modifier on accessor may only be used if property or indexer has both a get and a set accessor"
3. The accessibility modifier user 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 acces 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 know it is there. For more information on new language feature in C# 2.0, you can always check out the C# Programmung Guide on MSDN

7 komentar: