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; } }
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); } }
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; } } } }