13 - Properties in C#

13.1 Introduction to Properties

Properties are used to provide accessibility of classes variables in an application or outside an application. A property is a combination of variable and a method. They enable user to provide protection against the fields present in it. The internal implementation can be changed at run time.

A property is used to provide a flexible way to read, write, or calculate values of a private field. There are special methods called accessor for reading the private field data. The get property accessor is used to return property value to the user. The set accessor is used to assign a new value to the property.

Consider an example of class named result. It consists of private fields as subject, marks and percentage. User cannot directly access these fields outside the class it is defined. The properties are used to perform the function of accessing private fields.

13.2 Implementation of Properties

The accessors of a property contain the executable statements for setting and retrieving values from the user. A property can have a get accessor or a set accessor or both. The key benefit of the property is that it can be used in expressions and assignments like a normal variable. In actual the get and set accessors are automatically invoked.

The general syntax for property is as shown below:

public int number
{
    get
    {
        return number;
    }
    set
    {
        number=value;
    }
}
public string fname
{
    get
    {
        return fname;
    }
    set
    {
        fname = value; 
    }
}

Consider an example of class student. In the student class there are three fields as srno, name and subject.

class Program
{
    private int srno = 1;
    private string name = “John”;
    private string subject = “Maths”;
    public int Srno
    {
        get
        {
            return srno;
        }
        set
        {
            Srno = value;
        }
    }
    public string Name
    {
        get
        {
            return name;
        }
        set
         {
            name = value;
        }
}
public string Subject
{
    get
    {
        return subject;
    }
    set
    {
        subject = value;
    }
}
public override string ToString()
{
    return “Srno=”+Srno+”,Name=”+Name+”,Subject=”+Subject;
}
class Demo
{
    static void Main ( string[ ] args )
    {
        Program p =new Program();
        p.Srno = 1;
        p.Name = “Mark”;
        p.Subject = “Science”;
        Console.WriteLine(“Student Info:{0}”, p);
        Console.Read();
    }
}
}

 

The output for the code is as shown below:

In the above code, the get {} implementation is used to include a return statement. Any members of the class can be accessed through it. The set {} implementation receives the implicit argument. It is used for the assignment of the values in a variable.

13.3 Create Read – Only Property

Properties in C# can be made read only. The get accessor in the property is used for the implementation of the code. User can only access the variables but it cannot assign values to it.

The sample code for the read only property in C# is as shown below:

The output for the code is as shown below:

Class Camp
{
    int students = -1;
    string location = string.Empty;
    public Camp(int st1, string loc1)
    {
        students =st1;
        location = loc1;
    }
    public int st1
    {
        get
        {
            return students;
        }
    }
    public string loc1
    {
        get
        {
            return location;
        }
    }
    class Demo
    {
        static void Main ( string [ ] args )
        {
            Camp c = new Camp();
            Console.WriteLine(“Students : {0}, Location {1}”, c.st1, c.loc1);
            Console.Read();
        }
    }
} 

The output for the code is as shown below:

The Camp class has two read only properties as st1 and loc1. Each of these properties is read only because they have only get accessors. The values of st1 and loc1 are assigned in the code. The Main method initiates a new object of the Camp class named as c. The initialization of the c uses constructor of the Camp class taking parameters as integer and string type parameters. The values are 100 and London respectively.

13.4 Create Write – Only Property

User can assign values to a variable in a class. A write only property is for the assignment. User cannot read values from the write only property. The code to create a write only property is as shown below:

class Building
{
    int floors = -1;
    public int floorno
    {
        set
        {
            floors = value;
        }
    }
    private string buildingname = string.Empty;
    public string name
    {
        set
        {
            buildingname = value;
        }
    }
    public void Display()
    {
        Console.WriteLine(“floorno : {0}, name{1}”, floor, buildingname );
    }
    class Program
    {
        static void Main ( string[ ] args )
        {
            Building b = new Building();
            b.floors = 10;
            b.buildingname = “Imagica”;
            b.display();
            Console.Read();
        }
    }
}

The output for the code is as shown below:

In the above code, the set accessor is used. Due to which the property becomes as write only property. The values of the variables, floorno and name are assigned in the Main method of the code.

13.5 Auto Implemented Properties

The Auto Implemented properties of C# no coding is needed for the property accessors. The private field is created in the back field of an application. The back fields can be accessed only through the set and get access specifiers. This new feature of auto implemented properties was implemented in the 3.0 version of C#.

Advantages of using the Auto Implemented Properties in C#

1) They eliminate the confusion of removing the private member variable from the code view in an application

2) The client code and the internal code in an application are easy to access

3) The code is short compared to the traditional property declaration

4) It is easier to work when an intellisense is provided to the user

5) The control for accessing and setting values to the property is easy

6) They allow the programmer to validate the data before allowing a change on it

class Shopping
{
    public string brandname { get; set; }
    public double price { get; set; }
    public int items { get; set; }
    
    public shopping ( string bname, double Price, int Items )
    {
        brandname = bname;
        price = Price;
        items = Items;
    }
}
class Program
{
    static void Main ( string [ ] args )
    {
        Shopping s = new Shopping ( “Polo”, 2000, 4);
        Console.WriteLine(“Brandname : {0}, Price: {1}, Items {2}”, s.brandname, s.price, s,items);
        Console.Read();
    }
}

A sample code to demonstrate the auto implemented properties is as shown below:

The output for the code is as shown below:

In the above code, the get and set accessors do not have any implementations in the code. In the Auto Implemented property, the compiler creates the backing field having the same logic for the syntax of the traditional property. The values to the fields is passed through the Main() method in the code. It is similar to the constructor in C#.

The class used in the code is mutable. The values of the objects can be changed after they are created. Any values can be assigned to the objects created in an application.

Like us on Facebook