Properties in C# with Example

Properties in C# with Example
Properties in C# with Example

Before we start digging into properties, you need to know why we need properties.  Properties and access modifiers help in encapsulation.  Encapsulation in simple terms inclusion of one thing into another, so that the included thing should not be directly accessible or visible.  Encapsulation is one of the primary pillars of object oriented programming.  We have seen that we can easily create class fields and make them directly accessible through the class object, which is not a good approach at all.

Consider an example of Employee project (given below), where you have class field name of string type and this field stores a name, which will be further stored into a database.  Now, in each and every establishment every employee has a name, so it is obvious there should be at least something before storing that data into database.  But because that field is directly accessible, anyone can put some random value like numbers or even can leave that field blank and store that data into the database.  This is very dangerous.  To resolve this issue, we make use of properties, so that we can easily implement our own logic using if and else statements before storing that data into the database.

Unlike methods, properties do not contain any kind of parameter declaration.  Properties are of a certain data type and have an access modifier.  In properties, we make use of get and set accessors.  The get accessor will return the value and the set accessor will assign the value.  While assigning the value, we make use of value keyword, which contains a passed value to the property and we can assign it to any of the class fields.  All the public properties are accessible at object level.

Properties are of 4 types.

  • Read and write only.
  • Read only.
  • Write Only.
  • Auto-implemented.

Read and write only will contain both set and get accessors.  Read only will contain get accessor only.  Write only will contain set accessor only.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Hello
{
    class Employee
    {
        //class field
        string name;

        //Name property
        public string Name
        {
            get
            {
                return name;
            }

            set
            {
                if(string.IsNullOrEmpty(value))
                {
                    throw new Exception("Name cannot be null or empty.");
                }
                name = value;
            }
        }

        public void Print()
        {
            Console.WriteLine(name);
        }

    }


    class Program
    {
        static void Main(string[] args)
        {

            Employee emp = new Employee();
            emp.Name = "Roberto Carlos";
            emp.Print();

        }

    }
}

Output:

Roberto Carlos
Press any key to continue . . .

Sometimes, there is no requirement of any kind of logic before assigning a value to the class field using properties. For this reason in C# 3.0, Microsoft introduced auto-implemented properties.  In such cases, auto-implemented properties will generate a private anonymous field behind the scenes at compile time.  These auto-implemented properties are read and write only.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Hello
{
    class Employee
    {

        //Auto-Implemented property
        public string Name { get; set; }      
        

        public void Print()
        {
            Console.WriteLine(Name);
        }

    }


    class Program
    {
        static void Main(string[] args)
        {

            Employee emp = new Employee();
            emp.Name = "Roberto Carlos";
            emp.Print();

        }

    }
}

 Output:

Roberto Carlos
Press any key to continue . . .