Before talking about Property in C#, I want to tell you about other mechanisms that can also be used in place of properties.
Make the Class Field Public
Making the class fields public
and exposing to the external world is bad, as you will not have control over what gets assigned and returned. We can understand this with the help of the following program.
using System;
public class Student
{
public int ID;
public string Name;
public int PassMark = 35;
}
public class Program
{
public static void Main(string[] args)
{
Student s = new Student();
s.ID = -101;
s.Name = null;
s.PassMark = 0;
Console.WriteLine(“ID = {0} \nName = {1} \nPassing Marks = {2}”, s.ID, s.Name, s.PassMark);
Console.ReadLine();
}
}
Problems with public
fields:
ID
should always be non-negative number
Name
cannot be set to NULL
- If Student Name is missing “
No Name
” should be returned
PassMark
should be read only
To solve the above problem, we can use the following solutions:
1. Getter and Setter Methods
Programming languages that do not have properties use getter and setter methods to encapsulate the protect fields.
using System;
public class Student
{
private int _ID;
private string _Name;
private int _PassMark = 35;
public void SetId(int Id)
{
if (Id <= 0)
{
throw new Exception(“Student Id cannot be negative”);
}
this._ID = Id;
}
public int GetId()
{
return this._ID;
}
public void SetName(string Name)
{
if (string.IsNullOrEmpty(Name))
{
throw new Exception(“Student Name cannot be NULL or Empty”);
}
this._Name = Name;
}
public string GetName()
{
return string.IsNullOrEmpty(this._Name) ? “No Name” : this._Name;
}
public int GetPassMark()
{
return this._PassMark;
}
}
public class Program
{
public static void Main(string[] args)
{
Student s = new Student();
s.SetId(101);
s.SetName(“Akash”);
Console.WriteLine(“ID = {0} \nName = {1} \nMarks= {2}”, s.GetId(),s.GetName(),s.GetPassMark());
Console.ReadLine();
}
}
Note: In the above code, we created PassMark
field as read only by not creating a SetPassMark()
method.
2. Using Properties
A property is a member that provides a flexible mechanism to read, write, or compute the value of a private
field. Properties can be used as if they are public
data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.
Property can be following types:
- Read/Write Properties
- Read Only Properties
- Write Only Properties
- Auto Implemented Properties
In C# to encapsulate and protect fields, we use properties. We use get
and set
accessors to implement properties.
- Read/Write Properties: A property with both getand set accessor is a Read/Write property.
- Read Only Properties: A property with only get accessor is a Read only property.
- Write Only Properties: A property with only set accessor is a Write only property.
- Auto Implemented Properties: If there is no additional logic in the property accessors, then we can make use of auto- implemented properties introduced in C# 3.0.
Auto implemented properties reduce the amount of code that we have to write.
When we use auto-implemented properties, the compiler creates a private
, anonymous field that can only be accessed through the property’s get
and set
accessors.
We can understand Properties in C# with the help of the same program as we saw above but with the help of Properties. Auto Implemented Properties are also used in the following program:
using System;
public class Student
{
private int _ID;
private string _Name;
private int _PassMark = 35;
public int Id
{
set
{
if (value <= 0)
{
throw new Exception(“Student Id cannot be negative”);
}
this._ID = value;
}
get { return this._ID; }
}
public string Name
{
set
{
if (string.IsNullOrEmpty(value))
{
throw new Exception(“Student Name cannot be NULL or Empty”);
}
this._Name = value;
}
get {return string.IsNullOrEmpty(this._Name) ? “No Name” : this._Name; }
}
public int PassMark
{
get { return this._PassMark; }
}
public string Email { get; set; }
public string City { get; set; }
}
public class Program
{
public static void Main(string[] args)
{
Student s = new Student();
s.Id = 101;
s.Name = “Akash”;
s.City = “Pune”;
s.Email = “akash.jain@mail.com”;
Console.WriteLine(“ID = {0} \nName = {1} \nMarks= {2}”, s.Id, s.Name, s.PassMark);
Console.WriteLine(“City = {0} \nEMail= {1}”, s.City, s.Email);
Console.ReadLine();
}
}
Note: The advantage of properties over traditional Get()
and Set()
methods is that we can access them as if they were public
fields.
value
keyword (used in public int Id
property) - The contextual keyword value is used in the set
accessor in ordinary property declarations. It is similar to an input parameter on a method. The word value references the value that client code is attempting to assign to the property. In the above example, class Student
has a property called Id
that uses the value
parameter to assign a new number to the backing field _ID
.