I am assuming that you already know how to declare a variable and assign a value in a class. If you need more details, check out this free ebook - Beginning C# Object Oriented Programming.
In this article, I will answer the following three basic questions.
- What property is
- How can we implement a property
- How do we use a property
Introduction
C# properties are members of a C# class that provide a flexible mechanism to read, write, or compute the values of private fields, in other words, by using properties, we can access private fields and set their values. Properties in C# are always public data members. C# properties use get and set methods, also known as accessors to access and assign values to private fields.
Now the 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 read-only 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 three types of properties: Read/Write, ReadOnly and WriteOnly. Let's see each one by one.
Declare and read/write examples of property
We create an example that is used for the Name and Age properties of a Person. So first of all, create a Person class then we will use this class in an executable program.
Person. cs
namespace 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 Visual Studio IntelliSense that automatically shows object properties when we enter the dot (. ) operator after an object. In the following figure, we can see the 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 name in the set block, so this line of code actually assigns a value in the same 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 name private field by the Name Property because the Name property gets accessor returns a value of the private field name. So the private field is accessible by the property.
Create Readonly Property
We can also create a read-only property. Read-only means that we can access the value of a property but we 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 read-only 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 Property
We 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 Creation
We 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 Value
We 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 error.
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 to 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 calls 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 method
We 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 a bonus.
Auto mapped property
We can also create an auto-mapped property. When we create an auto-mapped property then we don't need define to the local private field in get and set accessors. For example, we have an employee class that has two properties, one in EmployeeId and another in Name. To define these properties we don't need to create a private field for these two properties 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 the executable program.
using System;
namespace PropertyExample
{
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();
}
}
}