Properties are special types of methods that provide a flexible mechanism for classes for exposing private fields. Hence these are called accessors.
There are two types of accessors under properties. These are:
- The get property accessors.
- The set property accessors.
These accessors are used to get, set as well as compute class member values.
Use of Properties in C#
The uses of different C# properties are:
- Properties have to be either read-only or write-only.
- Every property holds some specific logic while setting values for any particular work.
- Fields in properties are contained within the class private so that they cannot be accessed from another class or outside the class's scope straightforwardly.
Example of C# Properties
using System;
public class BoardMembers
{
private string mname, val = "Karlos ray";
public string memberName
{
get
{
return mname;
}
set
{
mname = val;
}
}
}
class TestBoardmem {
public static void Main(string[] args)
{
BoardMembers b1 = new BoardMembers();
b1.memberName = " Karlos Ray ";
Console.WriteLine(" Board member name is: " + b1.memberName);
}
}
Different Characteristics and Situations to Get and Set Accessors:
- Read and Write Properties: If your C# property holds both the get and the set methods.
- Read-Only Properties: If your C# property holds only, get the method defined in it.
- Write Only Properties: If your C# property holds only a set method defined in it.
- Auto-Implemented Properties: If there is no additional logic associated with your C# accessors, then auto-implemented property gets implemented.