Monday, November 1, 2021

C# Property as Class Member


Property

In C#, the concept of Property is a crossover concept of Field and Method. It means that it includes the features of field and method combined. In C#, property is a class member that is used to expose a field of a class to another class.

Before understanding  concept of property, let us understand that what are the shortcomings or limitations in the concept of field, due to which the concept of property is developed. The concept of property has evolved on the basis of the concept of field.

In a class, the first part is the data which is related to the fields and the second part is about the methods working on the data. Fields of a class are implicitly private by default. This means that any class's data or field is private by default and no other class can access that private field, but if another class wants to access that class's field, then the access modifier of the field should be explicitly public.

Field of class is kept private by default so that that field or its data is protected and cannot be unnecessarily manipulated by objects of another class. If a class's field is public, then any other class can manipulate that field. But sometimes there is such a business requirement in which we do not want to keep the field of the class public. In other words, we want to prevent the field or data of that class from being used directly by another class. In such a situation we have to make that field private.

Now one possibility is that by keeping the field private, we do not give the right to access it directly to another class, but at the same time we should take some such measures due to which it is possible to access that private field by another class, so for this, the concept of property have been developed. Although private fields can be exposed through public method even without property, but if you expose private field with the help of public method, then there is a possibility that another class can override or overload that method, etc., but A property is a programming construct that is created for the specific purpose of exposing the private field. There is no overriding or overloading of properties like methods. Therefore, the behavior of the property, despite being like a method, is different and special from the common method. Private fields can be exposed through public method even without property, the example of which is given below - 

namespace PropertyEx
{
    class Employee
    {
        string name;
        int age;
        //constructor
        public Employee(string name, int age)
        {
            this.name = name;
            this.age = age;
            
        }
        //method to get name field
        public string GetName()
        {
            return name;
        }
        //method to set name field
        public void SetName(string Name)
        {
            this.name = Name;
        }
        //method to get age field
        public int GetAge()
        {
            return age;
        }
        //method to set age field
        public void SetAge(int Age)
        {
            this.age= Age;
        }
    }
}

using System;
namespace PropertyEx
{
    class Program
    {
        static void Main(string[] args)
        {

            Employee e1 = new Employee("Amitabh", 15);
            Console.WriteLine("Original name: "+ e1.GetName());
            Console.WriteLine("Original age: " + e1.GetAge().ToString());
            e1.SetName("Amit");
            e1.SetAge (41);
            Console.WriteLine("New name: " + e1.GetName());
            Console.WriteLine("New age: " + e1.GetAge().ToString());
            Console.ReadKey();
        }
    }
}
In C#, a property is a special type of programming construct or method that allows to get or/and set fields of a class. Property enables the safe use of data under C# programming.

A property is a programming construct in C# that consists of get blocks or/and set blocks. Within the get block, we provide the right to gate of a field of a class to another class. Similarly, within the set block, we write the logic according to which another class can change a field of the current class to set. In this way, we can say that under C# programming, a property is a programming construct with the help of which a private field of a class can be obtained or set by an object of another class. It is to be remembered that a property class contains the logic of the gate being set for the same field. For example, if a class has three private fields then we have to provide three different properties for these three private fields within the class.

Property Syntactic Rules
To declare the property of any field we should follow the following syntactic rules
  1. The name of the property should match the name of the field so that it can be understood which field this property is for. For example, the name field of the property Name is appropriate.
  2. The datatype of both the fields whose property is to be created should be same. For example, the datatype of the name field is string, then the datatype of the property Name will also be string.
  3. The access modifier of the property should be given public so that it can be accessed by any other class. Others can also use other access modifiers, this is decided keeping in mind the needs of the business.
  4. A property block is denoted by { } like a class block. {} Property blocks contain get blocks and set blocks.
  5. Within the get and set block, the field of the class whose property get is set is used. There is a return statement within the get block whereas within the set block there is a contextual keyword called value.  

namespace PropertyEx
{
    class Employee
    {
        string name;
        int age;
        //constructor
        public Employee(string name, int age)
        {
            this.name = name;
            this.age = age;
            
        }
        public string Name 
        {
            get { return name; }
            set { name = value; }
        }
        public int Age
        {
            get { return age; }
            set { age = value; }
        }
    }
}

using System;

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

            Employee e1 = new Employee("Amitabh", 15);
            Console.WriteLine("Original name: "+ e1.Name);
            Console.WriteLine("Original age: " + e1.Age.ToString());
            e1.Name = "Rakesh";
            e1.Age = 30;
            Console.WriteLine("New name: " + e1.Name);
            Console.WriteLine("New age: " + e1.Age.ToString());
            Console.ReadKey();
        }
    }
}
  
It is not mandatory for a field within a class to have a property. If the field of a class is public then there is no need to create a property for that field.

Property is always created in relation to a field of the class. A property is related to one and only one field of the class.
A property can only implicate a get block or only a set can contain a set block, or it can contain both a get and a set block.
  • When the property contains only get block then such property is called readonly property.
  • When the property contains only set block then such property is called writeonly property.
  • When a property contains get and set blocks, such a property is called a readwrite property.
In C#, the return statement is always used in the get block of the property, while the value keyword is always used in the set block. The value keyword is a contextual keyword used to set a value in a field.

Convention of Naming Property in a Class
It is not necessary to define a property for all the fields within a class. If there are 50 fields within a class, it is not necessary to have a property for all those 50 fields. How does a programmer know for which field a property is defined? To detect this one has to scan the entire code block, which will take time. One programming convention to avoid this is to use an underscore before the name of the field whose property is to be created, which would imply that the field's property is defined within the class.

Properties of Concept of Property
1) The main purpose of a property is to limit or restrict access to a class's field. For example, access to a field of a class can be done by get or set or both can be done.
2) Another purpose of a property is to conditionally restrict access to a class's field. For example, access to a field of a class can be done with a get condition or a set condition, or both a condition.

Example of conditional access

namespace PropertyEx
{
    class Employee
    {
        string name;
        int age;
        //constructor
        public Employee(string name, int age)
        {
            this.name = name;
            this.age = age;
            
        }
        public string Name 
        {
            get { return name; }
            set
            {
                if (value != null && value.Length > 0)
                {
                    name = value;
                } }
        }
        public int Age
        {
            get { return age; }
            set
            {
                if (value > 18 )
                {
                    age = value;
                } }
        }
    }
}

using System;

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

            Employee e1 = new Employee("Amitabh", 15);
            Console.WriteLine("Original name: "+ e1.Name);
            Console.WriteLine("Original age: " + e1.Age.ToString());
            e1.Name = "Ajay";
            e1.Age = 27;
            Console.WriteLine("New name: " + e1.Name);
            Console.WriteLine("New age: " + e1.Age.ToString());
            Console.ReadKey();
        }
    }
}
  

Edited on 5th July 2023

No comments:

Post a Comment

Hot Topics