Properties in C#

Properties in C# with Examples:

In this article, I am going to discuss the Properties in C# with some examples. Please read our previous article before proceeding to this article where we discussed the Const and Read-Only Variables in C#. 

Why we need properties?

In order to encapsulate and protect the data members (i.e. fields), we use properties in C#. The Properties in C# are used as a mechanism to set and get the values of a class outside of that class. If a class contains any value in it and if we want to access those values outside of that class, then you can provide access to those values in 2 different ways

  1. By storing the value under a public variable we can give access to the value outside of the class.
  2. By storing that value in a private variable we can also give access to that value outside of the class by defining a property for that variable,

What is a Property in C#?

A property in C# is a member of a class which is used to set and get the data from a data field of a class. The most important point that you need to remember is. a property in C# is never used to store data, it just acts as an interface to transfer the data. We use the Properties as they are the public data members of a class, but they are actually special methods called accessors.

What are Accessors?

The Assessors are nothing but special methods which are used to set and get the values from the underlying data member. Assessors are of two types such as

  1. set accessor
  2. get accessor
What is set Accessor?

The set accessor is used to set the data (i.e. value) into a data field. This set accessor contains a fixed variable named “value”. Whenever we call the property to set the data, whatever data (value) we are supplying that will come and store in the variable “value” by default.

Syntax: set Data Field Name = value; }

What is Get Accessor?

The get accessor is used to get the data from the data field. Using this get accessor you cannot set the data.

Syntax: get return Data Field Name; }

What are the different types of properties supported by C#.NET?

The C#.NET supports four types of properties. They are as follows

  1. Read-only property
  2. Write only property
  3. Read Write property
  4. Auto-implemented property

Let us understand each of the above properties in details with examples.

What is Read-only Property?

The Read-only property is used to read the data from the data field. Using this property you cannot set the data into the data field. This property will contain only one accessor i.e. “get” accessor.

Syntax: AccessModifier Datatype PropertyName { get return DataFieldName; } }

What is Write only property?

The write-only property is used to write the data into the data field of a class. Using this property you cannot read the data from the data field. This property will contain only one accessor i.e. set accessor.

Syntax: AccessModifier Datatype PropertyName {  set DataFieldName = value; } }

What is Read Write property?

The Read-Write property is used for both read the data from the data field as well as write the data into the data field. This property will contain two accessor i.e. set and get.

Syntax:

AccessModifier DataType PropertyName 
{
           set { DataFieldName = value; }
           get { Return DataFieldName; }
}

NOTE: Whenever we create a property, the data type of the property must be the same as the data type of the data field for which we create the property. A property can never accept any arguments.

Let’s see an example to understand the Read and Write property.
namespace PropertyDemo
{
    public class Example
    {
        private int _empid, _eage;
        private string _ename, _eaddress;
        public int empid
        {
            set
            {
                _empid = value;
            }
            get
            {
                return _empid;
            }
        }
        public int eage
        {
            set
            {
                _eage = value;
            }
            get
            {
                return _eage;
            }
        }
        public string ename
        {
            set
            {
                _ename = value;
            }
            get
            {
                return _ename;
            }
        }
        public string eaddress
        {
            set
            {
                _eaddress = value;
            }
            get
            {
                return _eaddress;
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Example obj1 = new Example();
            obj1.empid = 101;
            obj1.ename = "pranaya";
            obj1.eage = 27;
            obj1.eaddress = "bbsr";
            Console.WriteLine("Employee details are:");
            Console.WriteLine("employee id:" + obj1.empid);
            Console.WriteLine("employee name:" + obj1.ename);
            Console.WriteLine("employee age:" + obj1.eage);
            Console.WriteLine("employee address:" + obj1.eaddress);
            Console.ReadKey();
        }
    }
}

OUTPUT:

Properties

In the above example, we declare the data fields of class Example as private. As a result, these data fields are not accessible directly from outside the class Example. So, here from the Program class, we transferred the data into the data field with the help of properties. As we are providing the abstraction to the data fields, this is known as data abstraction. So properties will provide data abstraction.

Let us see an example to understand the Read Only and Write Only properties in C#.
namespace PropertyDemo
{
    public class Example
    {
        int num1, num2, result;
        public int setnum1
        {
            set
            {
                num1 = value;
            }
        }
        public int setnum2
        {
            set
            {
                num2 = value;
            }
        }
        public int getresult
        {
            get
            {
                return result;
            }
        }
        public void add()
        {
            result = num1 + num2;
        }
        public void sub()
        {
            result = num1 - num2;
        }
        public void mul()
        {
            result = num1 * num2;
        }
        public void div()
        {
            result = num1 / num2;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Example obj1 = new Example();
            Console.WriteLine("ENTER ANY TWO NUMBERS");
            obj1.setnum1 = int.Parse(Console.ReadLine());
            obj1.setnum2 = int.Parse(Console.ReadLine());
            obj1.add();
            Console.WriteLine("the sum is:" + obj1.getresult);
            obj1.sub();
            Console.WriteLine("the sub is:" + obj1.getresult);
            obj1.mul();
            Console.WriteLine("the mul is:" + obj1.getresult);
            obj1.div();
            Console.WriteLine("the div is:" + obj1.getresult);
            Console.ReadKey();
        }
    }
}

OUTPUT:

properties in C#

What are the advantages of properties?
  1. Properties will provide the abstraction to the data fields.
  2. They also provide security to the data fields.
  3. Properties can also validate the data before storing into the data fields.
What is the default Accessibility modifier of Accessors?

The default accessibility modifier of the accessor is same as the accessibility modifier of property.

For example:

public int empid
{
   set { _empid = value; }
   get { return _empid; }
}

In the above example, property empid is declared as public. So, the set and get accessor will be public. If the property is private then the set and get will be private.

What is symmetric and asymmetric accessor?

If the accessibility modifier of the accessors (both get and set) are the same within a property then the accessors are known as symmetric accessors. On the other hand, if the accessibility modifier of the accessors is not the same within a property then the accessors are known as asymmetric accessors.

For example:

public int empid
{
          protected set { _empid = value; }
          get { return _empid; }
}

In the above example, the set accessor is declared as protected while the get is public, so they are known as asymmetric. In general asymmetric accessors are used in the inheritance process.

We can also write the Read-only property using two accessors like

public int empid
{
         private set { _empid = value; }
         get { return _empid; }
}
We can also write the Write only property using two accessors like
public int empid
{
        set { _empid = value; }
        private get { return _empid; }
}
Auto-Implemented properties in #

If you do not have any additional logic while setting and getting the data from a data field then you can make use of the auto-implemented properties which was introduced in C# 3.0

The Auto-implemented property reduces the amount of code that we have to write. When we use auto-implemented properties, the C# compiler implicitly creates a private, anonymous field behind the scene which is going to hold the data.

Syntax: Access specifier Datatype Property name get; set; }

Example: public int A Get; Set; }

Let’s see an example to understand auto implemented properties in C#.
namespace PropertyDemo
{
    class Test
    {
        public int A {get; set;}
        public int B { get; set; }
        public int Add()
        {
            return A + B;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Test obj = new Test();
            obj.A = 100;
            obj.B = 200;
            Console.WriteLine(obj.Add());
            Console.ReadKey();
        }
    }
}

OUTPUT: 300

Why we need properties in real time applications?

Declaring the class fields as public and exposing those fields to the outside class is bad as we do not have any control over what gets assigned and returned.

Let’s understand this with one example.
namespace PropertyDemo
{
    public class Student
    {
        public int ID;
        public string Name;
        public int PassMark;
    }
    class Program
    {
        static void Main(string[] args)
        {
            Student s = new Student();
            s.ID = -100;
            s.Name = null;
            s.PassMark = 0;
            Console.WriteLine("ID = {0} && Name = {1} && PassMark = {2}", s.ID, s.Name, s.PassMark);
            Console.ReadKey();
        }
    }
}

OUTPUT:

properties in C#

Problems with the above public fields are as follows
  1. An ID value should always be a non-negative number.
  2. The name cannot be set to NULL.
  3. If a student name is missing then we should return “No Name”.
  4. The PassMark value should always be read-only.

Programming languages that do not have properties use getter and setter methods to encapsulate and protect fields.

Let’s rewrite the same program using setter and getter methods to achieve the above requirements.
namespace PropertyDemo
{
    public class Student
    {
        private int _iD;
        private string _name;
        private int _passMark = 35;
        public void SetID(int ID)
        {
            if (ID < 0)
            {
                throw new Exception("ID value should be greater than zero");
            }
            this._iD = ID;
        }
        public int GetID()
        {
            return this._iD;
        }
        public void SetName(string Name)
        {
            if (string.IsNullOrEmpty(Name))
            {
                throw new Exception("Name should not be empty");
            }
            this._name = Name;
        }
        public string GetName()
        {
            if (string.IsNullOrEmpty(_name))
            {
                return "No Name";
            }
            return this._name;
        }
        public int GetPassMark()
        {
            return this._passMark;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Student S = new Student();
            S.SetID(101);
            S.SetName("Pranaya");
            Console.WriteLine("Student ID = {0}", S.GetID());
            Console.WriteLine("Student Name = {0}", S.GetName());
            Console.WriteLine("Studenr Pass Mark = {0}", S.GetPassMark());
            Console.ReadKey();
        }
    }
}

OUTPUT:

Understanding Properties using C#

Note: The advantage of properties over traditional getter() and setter() method is that we can access them as they are public fields.

Let’s rewrite the same program using properties to achieve the above requirements.
namespace PropertyDemo
{
    public class Student
    {
        private int _id;
        private string _name;
        private int _passMark = 35;
        public int ID
        {
            set
            {
                if (value < 0)
                {
                    throw new Exception("ID value should be greater than zero");
                }
                this._id = value;
            }
            get
            {
                return this._id;
            }
        }

        public string Name
        {
            set
            {
                if (string.IsNullOrEmpty(value))
                {
                    throw new Exception("Name should not be empty");
                }
                this._name = value;
            }
            get
            {
                return string.IsNullOrEmpty(this._name) ? "No Name" : this._name;
            }
        }
        public int PassMark
        {
            get
            {
                return this._passMark;
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Student S = new Student();
            S.ID = 101;
            S.Name = "Pranaya";
            Console.WriteLine("Student ID = {0}", S.ID);
            Console.WriteLine("Student Name = {0}", S.Name);
            Console.WriteLine("Studenr Pass Mark = {0}", S.PassMark);
            Console.ReadKey();
        }
    }
}

OUTPUT:

C# Properties

In the next article, I am going to discuss the use of ToString() Method in C# and then we will discuss why we should override the ToString method in C# with some examples.

In this article, I try to explain Properties in C# step by step with some simple examples. I hope you understood the need and use of Properties in C#.

Leave a Reply

Your email address will not be published. Required fields are marked *