In the C#, Property is a member of a class that provides a flexible mechanism for classes to expose private fields which is special methods called accessors. A C# property has two accessors, get property accessor and set property accessor
Usage of C# Properties
- C# Properties can be read-only or write-only.
- We can have logic while setting values in the C# Properties.
- We make fields of the class private so that fields can't be accessed from outside the class directly. Now we are forced to use C# properties for setting or getting values.
C# Properties Example
using System;
public class EmployeeInfo
{
private string Name;
public string Name1
{
get
{
return Name;
}
set
{
Name = value;
}
}
}
public class AnotherClassEmployeeInfo{
public static void Main(string[] args)
{ EmployeeInfo objEmployeeInfo = new EmployeeInfo();
objEmployeeInfo.Name1 = "Sylvia Neupane";
Console.WriteLine("Employee Name: " + objEmployeeInfo.Name1);
}
}
Output
Employee Name: Sylvia Neupane
C# Properties Example 2: having logic while setting value
using System;
public class EmployeeInfo
{
private string Name;
public string Name1
{
get
{
return Name;
}
set
{
Name = value+" FindAndSolve";
}
}
}
public class AnotherClassEmployeeInfo{
public static void Main(string[] args)
{
EmployeeInfo objEmployeeInfo = new EmployeeInfo();
objEmployeeInfo.Name1 = "Sylvia Neupane";
Console.WriteLine("Employee Name: " + objEmployeeInfo.Name1);
}
}
Output
Employee Name: Sylvia Neupane FindAndSolve
C# Properties Example 3: read-only property
using System;
public class EmployeeInfo
{ private static int counter;
public EmployeeInfo()
{
counter++;
}
public static int Counter { get
{
return counter;
}
}
}
public class AnotherclassEmployeeInfo{
public static void Main(string[] args)
{ EmployeeInfo e1 = new EmployeeInfo();
EmployeeInfo e2 = new EmployeeInfo();
EmployeeInfo e3 = new EmployeeInfo();
Console.WriteLine("No. of Employees: " + EmployeeInfo.Counter);
}
}
Output
No. of Employees: 3