Ads

C# Programming 3 - Why do we need properties, Because we have fields in class?

Hello All,

Welcome to C# Programming, I am Chakrapani Upadhyaya a full stack engineer.

In this article we will understand that why we use properties and what is not possible with our class fields.

 


This is the most commonly asked question in almost C# interviews. But most of us stuck in this question and try to find some unrelated answers.

But really that might creates bad impressions right?

OK!... Lets Discuss on this...

First, we see what is fields?

Fields:

Fields are actual variables in your object that stores a particular piece of information, example shown below.

public class Program
{
    public static void Main(string[] args)
    {
        //Creating object of MyPropAndFields class
        MyPropAndFields propObj = new MyPropAndFields();


        //We have full control on MyId variable now we can retrieve, 
        //we can write value to it
        propObj.MyId = "ID123";


        //Display the MyId value in console
        Console.WriteLine($"My Id Value is : {propObj.MyId}");


        Console.Read();
    }
}



public class MyPropAndFields
{
    public string MyId;


    public string GetMyId()
    {
        return MyId;
    }
}

In the above example, MyId is class field which stores ID information. Everyone who creates the object of the MyPropAndFields class can read or write to the MyId  field.

 

We cannot restrict anything with fields.

Properties:

Properties offer another level of abstraction to expose the fields.

In General word Properties are used to restrict direct access to member variables of a class.

Because We should keep class fields(variable) as private always and accessed via get and set properties, Examples shown below.

Compared to Fields, Properties comes with below features...

1. You can have read-only properties and additional accessors as mentioned by others.


public class Program
{
    public static void Main(string[] args)
    {
        MyPropAndFields propObj = new MyPropAndFields();

        Console.WriteLine($"Initial Discount Value Is : {propObj._discount}");

        Console.WriteLine($"Discount after Method Call : {propObj.GetOfferedDiscount()}");

        Console.Read();
    }
}

public class MyPropAndFields
{
    private int Discount;

    public int _discount
    {
        get
        {
            return Discount;
        }
    }

    public int GetOfferedDiscount()
    {
        Discount = 30;
        return Discount;
    }
}


In this above example Discount is set to read-only with the help of  properties, now one can write to this except they can get the value.




 2. We Can execute statements inside Properties

public class Program
{
    public static void Main(string[] args)
    {
        MyPropAndFields propObj = new MyPropAndFields();

        Console.WriteLine($"Next Date is : {propObj._nextDate}");

        Console.Read();
    }
}

public class MyPropAndFields
{
    public DateTime _nextDate
    {
        get
        {
            return GetNextDate();
        }
    }

    public DateTime GetNextDate()
    {
        DateTime dateTime = DateTime.Now;
        return dateTime.AddDays(1);
    }
}

In the above example we are calling the function GetNextDate() and it returns the next day date.

3. We can validate the input value before assigning to fields.

public class Program
{
    public static void Main(string[] args)
    {
        MyPropAndFields propObj = new MyPropAndFields();

        propObj._age = 0;

        Console.WriteLine($"Finally Age Is : {propObj._age}");

        Console.Read();
    }
}

public class MyPropAndFields
{
    public int Age { get; set; }
    public int _age
    {
        get
        {
            return Age;
        }
        set
        {
            if (value == 0)
            {
                Age = 10;
            }
            else
            {
                Age = value;
            }
        }
    }

}

In the above example we are validating the variable age. If age is 0 then we set the value as 10.

4. We can Debug the value inside property

Consider we are using Field to hold a value. At some point we need to debug and check where the value is getting null for that field. It will be difficult to do where the number of lines of code are more than 10000. In such situations we can use Property and can set debug mode inside

I hope you enjoyed the article, Please let me know in case any concerns.

Until then take care bye, see you in next article.

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !