I am assuming that you know how to declare a variable and how to assign a value to the variable. In this article I am trying answer three basic questions. These are:
IntroductionProperties are members that provide a flexible mechanism to read, write or compute the values of private fields, in other words by the property we can access private fields. In other words we can say that a property is a return type function/method with one parameter or without a parameter. These are always public data members. It uses methods to access and assign values to private fields called accessors.Now question is what are accessors?The get and set portions or blocks of a property are called accessors. These are useful to restrict the accessibility of a property, the set accessor specifies that we can assign a value to a private field in a property and without the set accessor property it is like a readonly field. By the get accessor we can access the value of the private field, in other words it returns a single value. A Get accessor specifies that we can access the value of a field publically.We have the three types of properties Read/Write, ReadOnly and WriteOnly. Let's see each one by one.Declare and read/write example of propertyWe create an example that is used for the Name and Age properties for a Person. So first of all create a Person class then we will use this class in an executable program.Person.csnamespace PropertyExample{ public class Person { private string mName = string.Empty; private int mAge = 0; public string Name { get { return mName; } set { mName = value; } } public int Age { get { return mAge; } set { mAge = value; } } }}Now we use this class in an executable program by creating an object of the Person class. It is VS intellisence that automatically shows object properties when we enter the dot (. ) operator after an object. In the following figure we can see Age and Name properties of a Person.Now we read and write values for the property.Finally we get the output of this program:Let's see the line of code:objPerson.Name = "Sandeep Singh";This line of code is called the set accessor of the Name property in the Person class where we are using the private field mName in the set block, so this line of code actually assigns a value in the mName field, in other words we can assign a value to the private field by property.Console.WriteLine("Your Name is :{0}", objPerson.Name);This line of code is called a get accessor of the Name Property in the Person class, in other words we can access the mName private filed by the Name Property because the Name property get accessor returns a value of the private field mName. So the private field is accessible by the property.Create Readonly PropertyWe can also create a read only property. Read only means that we can access the value of a property but can't assign a value to it. When a property does not have a set accessor then it is a read only property. For example in the person class we have a Gender property that has only a get accessor and doesn't have a set accessor. The Person class is:public class Person{ public string Gender { get { return "Male";} }}When we assign a value to the Gender Property of the Person class object then we get an error that it is a readonly property and can't assign a value to it.So the Gender property of the Person class always returns a value and we can't assign a value to it.Create WriteOnly ProertyWe can also create a write only property. A write only property is a property that we can assign a value to but can't get that value because that property doesn't have a get accessor. For example we have a Person class that has the property FirstName that has a set accessor but doesn't have a get accessor so it is a write only property.
public class Person
{
private string mFirstName = string.Empty;
public string FirstName
{
set{mFirstName = value;}
}
}
When we access the value of the FirstName property then we get an error like:We can create a write only property when we don't define a get accessor.Assign Values to Properties on Object CreationWe can also assign values to properties when we are creating an object of the class. For example when we create a Person class object then we can assign a Name and Age property to the person object.Person objPerson = new Person(){ Name = "Sandeep Singh", Age = 24};Properties of objects are a block defined by curly braces and in the block each property will be separated by a comma.Validate Property ValueWe can validate a value of a property before it's set to a variable, in other words we can check a value to be assigned to a private field and if it is correct then it will be assigned to the private field otherwise it will give an erorr.Suppose you are a citizen of India and participate as a voter in a parliament election so your age should be greater than or equal to 18 otherwise you can't vote. To implement this function we have a Voter class and that class has an Age property. The Age property can have a value greater than or equal to 18 otherwise it will show 0 for the age with a message. Our Voter class is:
using System;namespace PropertyExample{ public class Voter { private int mAge = 0; public int Age { get { return mAge; } set { if (value >= 18) { mAge = value; } else { Console.WriteLine("You are not eligible for voting"); } } } }}Now create an executable program by which we assign an age value of a Voter.
using System;namespace PropertyExample{ class Program { static void Main(string[] args) { Voter objVoter = new Voter(); Console.WriteLine("Please enter your age"); objVoter.Age = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Your age is :{0} years", objVoter.Age); Console.ReadKey(); } }}Now we enter a value less than 18 and then we get a message with 0 years.In the output screen above we get a message from the set accessor and the value isn't set in the private field so we get a default value of the private field that we already set 0. Don't be confused by the message and return value. Here set is not returning a value. It is just printing a message on the console before the get accessor cals the Age property. The following picture shows the message shown before calling the get accessor.If we use a value greater than or equal to 18 then we get the private field value without a message.Use of Property as a methodWe can also use a property instead of a method that has one parameter and a return value. Because we can define custom logic in the get and set accessors.Suppose we have a rule for a student that when a student gets marks greater than or equal to 80 then they get 5 bonus marks and when they get marks greater than or equal to 70 but less than or equal to 79 then they get 2 bonus marks. So we define logic in the get accessor that adds marks depending on the student's original marks and thereafter the total marks (original marks + bonus marks) of the student will be returned.
using System;namespace PropertyExample{ public class Student { private int mMarks = 0; public int Marks { get { if(mMarks >= 80) { mMarks+=5; } else if(mMarks <= 79 && mMarks>=70 ) { mMarks+=2; } return mMarks; } set { mMarks = value; } } }}Now create a program by which we can input student marks.
using System;namespace PropertyExample{ class Program { static void Main(string[] args) { Student objStudent = new Student(); Console.WriteLine("Please enter your marks"); objStudent.Marks = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Your marks are :{0} marks", objStudent.Marks); Console.ReadKey(); } }}Now we enter more than 80 marks and get the total marks with bonus.
Auto mapped property
We can also create auto mapped property. When we create auto
mapped property then we don't need define to local private field in get and set
accessors. For example we have an employee class which has two property one in
EmployeeId and another is Name. To define these property we don't need to
create private field for these two property and directly declare it.
namespace
PropertyExample
public class Employee
public int EmployeeId { get;
set; }
public string Name { get; set; }
Now we access Employee class property in executable program.
using
System;
class Program
static void Main(string[]
args)
{
Employee
objEmployee = new Employee()
{
EmployeeId = 1001,
Name = "Sandeep"
};
Console.WriteLine("Employee Id is :{0} and Employee Name is :{1}",
objEmployee.EmployeeId, objEmployee.Name);
Console.ReadKey();
}
View All