Properties in C#

 Properties in C#


Introduction:

To understand the need for properties, let us understand what is the problem with this the below class?

public class Person
{
    public int Id;
    public string? Name;
}

The problems with this class is that it violates Encapsulation. Whoever uses this class can set any value for Id and Name. I mean the Id could be negative and name could be null.

To solve this problem, we can rewrite our class as below:


public class Person
{
    private int Id;
    private string? Name;


    public void SetId(int id)
    {
        if (id < 0)
        {
            throw new ArgumentOutOfRangeException("id");
        }
        this.Id = id;
    }

    public int GetId()
    {
        return this.Id;
    }
}

Here, we have a getter and setter functions. This is common in any programming language.


What C# provides us to solve this problem?


In C#, we use get and set accessors to implement properties; A property with *only* get will be a Read-only field. A property with *only* set will be a Write-only field. A property with both get and set will be Read/Write property.


The major advantage of using set and get accessors over the traditional method is that we can access them as if they are a public field.



To solve the same problem as above using set and get, we write the code as below:

public class Person
{

    private int _id;
    public int Id
    {
        set
        {
            if (value < 0)
            {
                throw new ArgumentOutOfRangeException("id");
            }
             this._id = value;
        }

        get 
        {
             return this._id; 
         
    }
}


This code is cleaner and better.