This tutorial is about how to define property in C#. Property is a member of a class that provide flexibility and security to the private member fields
Don't forget to check out our site http://howtech.tv/ for more free how-to videos!
http://youtube.com/ithowtovids - our feed
http://www.facebook.com/howtechtv - join us on facebook
https://plus.google.com/103440382717658277879 - our group in Google+
Introduction
Property is a member of a class that provides flexibility and security to the private member fields. This helps in reading and writing the value to the private field. The properties can also be referred to as accessors.
To define property in C#, we can use any access modifiers. The concept behind the properties is encapsulation.
Follow the step by step guide below and learn how to define property in C#.
Step 1: Define Property
Let us look into the following code snippet:
public int Currentgrade
{
get { return grade; }
set { grade = value; }
}
Currentgrade sets and gets the data for the member field grade. Thus the grade is encapsulated from the rest of the program while it is accessible only by the property. The set accessor sets the value for the grade while the get accessor returns a value for the grade. The value keyword here is auto-generated in C# and this refers to the value the user sets to the member field grade.
The preceding code is the perfect example of what a get and set accessor do. Hence the code can be further simplified, if there is no custom code required as follows:
public int Currentgrade
{
get;
set;
}
Step 2: Access Property
To access the get and set accessors, you need to create an object and call the accessors as follows:
Lets use the previous example of info class.
Info myInfo = new Info();
myInfo.Currentgrade = 5; //To set the value
int i = myInfo.Currentgrade; //To get the value
You can make the private member field a read-only or a write-only property.
Conclusion
Consider the following example:
You have marks of certain students and want to compute the grade. Grade can be calculated using marks. Hence there is no value to be set. Thus using only the get accessor, you make it a read-only property. Look into the following code snippet:
public int mark;
public int Currentgrade
{
get{return mark/10;}
}
By having a set accessor, the field is made a write-only property. There is no wide implementation of a write-only property. And that's a basic introduction on how to define properties.