C#: Automatic Properties

This entry is part 29 of 71 in the series C#

A variable or a method inside a class could be called properties of a class or object in other object-oriented programming languages such as C++.

A property in C++ has a slightly different meaning.  It provides a simple way to access a field, called the backing field.

The backing field can be publicly available while still allowing the internal details of that field to be hidden.

Although fields declare variables, which require storage in memory, properties do not.

Instead, properties are declared with accessors that enable you to control whether a value can be read or written and what should occur when doing so.

The get accessor enables the property value to be read, whereas the set accessor enables the value to be written.

using System;

namespace Automatic
{
    class Employee
    {
        public string Name
        {
            get;
            set;
        }
    }

    class Program
    {
        static void Main()
        {
            Employee e1 = new Employee();
            e1.Name = "John";  //This will set name to John
            Console.WriteLine(e1.Name);  //This will get the name
            Console.ReadLine();
        }
    }
}

Now we look at the code here:

class Employee
{
   public string Name
     {
        get;
        set;
     }
}

It shows the simplest way to declare a property.

When using this syntax, known as automatic properties, you omit the backing field declaration and must always include both the get and set accessor without a declared implementaion, which the compiler provides.

In fact the compiler transforms the code into code that looks like below shown in the previous example.

class Employee
{
   private string name;

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

You can refer to a later post about array where I have used the length property of an array to easily retrieve the array length.

 

Series Navigation<< C#: get and set accessors
C#: Using property to retrieve string length >>

Leave a comment

Leave a Reply