Properties in C#

Properties are an extension of fields. You can access the properties like normal fields declared in the class. A property contains with get and set accessors. The accessors are used to get and set the value of a variable. Each property has a name and a type. Type cannot be void. You can create static, instance, abstract, and virtual properties.

Properties also enables you to write some logic in it.

The general form of a property is given below:

type property_name {
get {
         // get accessor code
     }
set {
         // set accessor code
     }
}


Here, type specifies the type of the property, such as int, string, float etc., and property_name is the name of the property. It is important to note that properties do not have any storage locations. Let us take an example and discuss.

Example

using System;
using System.Collections;
namespace ConsoleApplication1
{
    public class Employee
    {        
        string empName;
        int empAge;
        public Employee()
        {
            this.empName ="N/A";
            this.empAge = 0;
        }
        public string Name
        {
            get { return empName; }
            set { empName = value; }
        }        
        public int Age
        {
            get { return empAge; }
            set
            {
                if(value>0)
                empAge = value;
            }
        }     
    }
    class Program
    {
        static void Main(string[] args)
        {
            Employee obj = new Employee();
            Console.WriteLine("Enter Employee Name");
            obj.Name = Console.ReadLine();
            Console.WriteLine("Enter Employee Age");
            obj.Age = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Employee Name ={0} , Employee Age ={1}",  
            obj.Name,obj.Age);
            Console.ReadLine();
        }
    }
}


Let’s discuss the above code. The class employee defines two private field empName and empAge and two public properties called Name and Age. The properties Name and Age are specified as public so it can be accessed by code outside of its class.

As you know that a property does not have a storage location. In general properties are access the private fields of class.

The get accessor simply returns the value of Name and Age properties. The set accessor sets the value of Name and Age properties.

The above written properties Name and Age are called as read-write property because it allows it allows to be read and write fields. It is possible, however, to create read-only and write-only properties. For creating a read-only property, define only a get accessor and for a write-only property, define only a set accessor.

When you define a property, the compiler automatically generates the methods for properties. If you have created a property, in which you defined the get and set accessor, then compiler will create two methods, one for get and another for set accessor.

If you have created read only or write only property, then it will create only one method (Depends upon get or set accessor).

As we have created Employee type, the compiler emits four method definitions for Employee type, because both properties have get and set accessor Methods.
You can see these methods by using ILDASM tool of visual studio. For viewing this information, open command prompt of visual studio and type the ILDASM and enter. You will get a window. Open the exe file of your program with the help of this window. You will get the result as given below for employee class.

properties employee class

Auto-Implemented Properties

Creating Auto-Implemented Properties is very simple. It allows you to create properties without get and set accessor implementations. It means that accessors for an auto-implemented property have no bodies.

If you use an Automatic Property in your application and later requirement is change so decide to do something logical in the set or get, you can easily change your code without disturbing the other code.

Example

using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
    public class Employee
    {             
        public Employee()
        {
            this.Name ="N/A";
            this.ID = 0;
        }
        public Employee(int id,string name)
        {
            this.ID = id;
            this.Name = name;
        }
        public int ID{ get; private set;}
        public string Name { get; private set; }             
        public static List<Employee> GetEmployees()
        {
            List<Employee> list = new List<Employee>();
            list.Add(new Employee(1,"Raj"));
            list.Add(new Employee(2,"Digvijay"));
            list.Add(new Employee(3,"Jenifer"));
            list.Add(new Employee(4,"Heena"));
            return list;
        }               
    }
    class Program
    {
        static void Main(string[] args)
        {
            Employee obj = new Employee();
           foreach(Employee emp in Employee.GetEmployees())
           {
               Console.WriteLine("Employee ID ={0} , Employee Name ={1}", emp.ID, emp.Name);
           }
            Console.ReadLine();
        }
    }
}


When you declare an auto implemented property, then the compiler will automatically declare private field in its class.

In this example, the field will be of type String, the type of the property. And, the compiler will automatically implement the get_Name and set_Name methods for you to return the value in the field and to set the field’s value, respectively.