#702 – An Automatic Property Must Define Both get and set Accessors

When you define an automatic property, you must include both get and set accessors.

        public string Name { get; set; }

It wouldn’t make sense to omit either accessor, since they are the only mechanism for reading from or writing to the property.

Although you can’t strictly create a read-only or write-only automatic property, you can use access modifiers so that the property is effectively read-only or write-only, from outside the class.

        // Automatic property that is read-only from outside class
        public string Temperament { get; protected set; }

        // Automatic property that is write-only from outside class
        public string Password { protected get; set; }
Advertisements

#261 – How Automatic Properties Look Under-the-Covers

The typical pattern for implementing an automatic property in a C# class is shown below–you do not need to define either a private backing variable, or the bodies of the get and set accessors.

    public class Dog
    {
        // An automatic property
        public string Name { get; set; }
    }

It’s interesting to use the IL DASM tool to see how this property is actually implemented.  Start up the IL Disassembler tool and then do a File | Open and load the .exe containing the property shown above.  You’ll see the following:

You can see the backing variable that the compiler automatically generated–k__BackingField.  You can also see the get and set accessors that the compiler automatically created, get_Name and set_Name.

#252 – Automatic Properties

The typical syntax for a property implementation in C# is to define the public interface for the property and then have the implementation of the get and set accessors for the property read/write to a private backing variable.

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

C# provides a shortcut for this structure through the use of automatic properties.  You can avoid declaring the private backing variable and implementing the get/set accessors by simply declaring the get/set accessors without a body.

        public string Name { get; set; }

When you declare a property this way, it appears exactly the same to any client code.  The underlying code generated by the compiler is also the same–a public property with a backing variable–but you don’t actually have access to the backing variable.