Properties in C# : How/Why we use this?

Again, one of my follower on Facebook asked me a question, here it is.


Hello Sir

I'm new in C#, i tried lot to understand the get/set properties but still can't understand. Please help, why and how we use this?
by Manish Kumar


And this blog post is my response to his ask. So, let’s get started.


Friend, you don’t need to use set or get properties, you could write separate methods for that too. Let’s look at the demo program with properties (traditional way).

Without Properties

class Student
{
    static void Main(string[] args)
    {
        StudentMethod std = new StudentMethod();
        std.SetRoll(1);
        std.SetName("Abhimanyu");
        Console.WriteLine("Roll: {0} and Name: {1}", std.GetRoll(), std.GetName());
        Console.ReadKey();
    }
}

public class StudentMethod
{
    private int Roll = 1;

    public int GetRoll()
    {
        return Roll;
    }

    public void SetRoll(int r)
    {
        Roll = r;
    }

    private string Name = string.Empty;

    public string GetName()
    {
        return Name;
    }

    public void SetName(string n)
    {
        Name = n;
    }
}

The StudentMethod class has four methods, two for each private field that the class encapsulates: Roll and Name. As you can see, SetRoll and SetName assign a new values and GetRoll and GetName return values.

Observe how Main calls the SetRoll and SetName methods, which sets Roll to 1 and Name to "Abhimanyu" in the StudentMethod instance, std.  The call to Console.WriteLine demonstrates how to read Roll and Name from std, via GetRoll and GetName method calls, respectively.

This is actually real pain for developers to write such a long set of Methods. Even this is such a common pattern, that C# has embraced it in the form of a language feature called properties.

Features of Properties

There are a few reasons to use properties, instead of public fields/methods.

(i)           Properties can be virtual.
(ii)          You can make the setters for a property private.
(iii)         Properties have a 'special' meaning to things that inspect classes at runtime.

With Properties

class Student
{
    static void Main(string[] args)
    {
        StudentMethod std = new StudentMethod();
        std.Roll = 1;
        std.Name = "Abhimanyu";
        Console.WriteLine("Roll: {0} and Name: {1}", std.Roll, std.Name);
        Console.ReadKey();
    }
}

public class StudentMethod
{
    public int Roll { get; set; }
    public string Name { get; set; }
}

Notice how the get and set accessors in above example do not have implementations, it is just an auto-implemented property. In an auto-implemented property, the C# compiler creates the backing store field behind the scenes, giving the same logic that exists with traditional properties, but saving you from having to use all of the syntax of the traditional property. As you can see in the Main method, the usage of an auto-implemented property is exactly the same as traditional properties.


This was a read and write property, but you can also create read-only properties or write-only properties.

Read-Only Properties

class Student
{
    static void Main(string[] args)
    {
        StudentMethod std = new StudentMethod(1, "Abhimanyu");
        Console.WriteLine("Roll: {0} and Name: {1}", std.ro, std.na);
        Console.ReadKey();
    }
}

public class StudentMethod
{
    private int Roll = 1;
    private string Name = string.Empty;

    public StudentMethod(int r, string n)
    {
        Roll = r;
        Name = n;
    }

    public int ro
    {
        get
        {
            return Roll;
        }
    }

    public string na
    {
        get
        {
            return Name;
        }
    }
}

The StudentMethod class in above example has two read-only properties, Roll and Name. You can tell that each property is read-only because they only have get accessor. At some time, values for the Roll and Name must be assigned, which is the role of the constructor.

The Main method of the Student class instantiates a new StudentMathod object named std. The instantiation of std uses the constructor of StudentMethod class, which takes int and string type parameters. In this case, the values are 1 as r and "Abhimanyu" as n. This initializes the Roll and Name fields of std.

Since the Roll and Name properties of the StudentMethod class are read-only, there is no other way to set the value of the Roll and Name fields. If you inserted std.Roll = 1 into the listing, the program would not compile, because Roll is read-only; the same with Name field. When the Roll and Name properties are used in Console.WriteLine, they work fine. This is because these are read operations which only invoke the get accessor of the Roll and Name properties.

Write-Only Properties

class Student
{
    static void Main(string[] args)
    {
        StudentMethod std = new StudentMethod();
        std.ro = 1;
        std.na = "Abhimanyu";

        std.DisplayStudentMethod();

        Console.ReadKey();
    }
}

public class StudentMethod
{
    private int Roll = 1;
    private string Name = string.Empty;

    public void DisplayStudentMethod()
    {
        Console.WriteLine("Roll: {0} and Name: {1}", Roll, Name);
    }

    public int ro
    {
        set
        {
            Roll = value;
        }
    }

    public string na
    {
        set
        {
            Name = value;
        }
    }
}

This time, the get accessor is removed from the Roll and Name properties of the StudentMethod class. The set accessors have been added, assigning value to the backing store fields, Roll and Name.

The Main method of the Student class instantiates the StudentMethod class with a default constructor. Then it uses the ro and na properties of std to set the Roll and Name fields of std to 1 and "Abhimanyu", respectively. This invokes the set accessor of Roll and Name properties from the std instance.

I hope my answer is satisfactory for my friend. Thanks.

Comments

Post a Comment

Popular posts from this blog

Migrating database from ASP.NET Identity to ASP.NET Core Identity

Customize User's Profile in ASP.NET Identity System