In this article, we will find out about the C# properties, kinds of properties (set and get) with example.
C# properties
Properties are the individuals from a class, interface, and structure in C#. As we realize that, individuals or techniques for class and structure are known as “Fields“. Properties are an all-inclusive rendition of fields with the practically same syntax.
Utilizing properties, we can peruse and compose or control private fields. For example, we have a class name EMPLOYEE that contains private fields EMP_ID, EMP_NAME, EMP_SALARY. Ordinarily, we can’t get to those fields out of the class. However, utilizing Properties we can get to them.
Sorts of C# properties
There are two sorts of properties are utilizing to get to private fields:
- set – To compose value in private fields
- get – To peruse the value of private fields
Statement:
public int ID
{
get
{
return EMP_ID;
}
set
{
EMP_ID = value;
}
}
public string NAME
{
get
{
return EMP_NAME;
}
set
{
EMP_NAME = value;
}
}
public int SALARY
{
get
{
return EMP_SALARY;
}
set
{
EMP_SALARY = value;
}
}
Example: With the assistance of the program, we can comprehend about properties effectively…
using System;
using System.Collections;
namespace ConsoleApplication1
{
class EMPLOYEE
{
private int EMP_ID ;
private string EMP_NAME ;
private int EMP_SALARY ;
public int ID
{
get
{
return EMP_ID;
}
set
{
EMP_ID = value;
}
}
public string NAME
{
get
{
return EMP_NAME;
}
set
{
EMP_NAME = value;
}
}
public int SALARY
{
get
{
return EMP_SALARY;
}
set
{
EMP_SALARY = value;
}
}
}
class Program
{
static void Main()
{
EMPLOYEE E = new EMPLOYEE();
E.ID = 101;
E.NAME = "Duggu Pandit";
E.SALARY = 1000000;
Console.WriteLine("ID : " + E.ID);
Console.WriteLine("NAME : " + E.NAME);
Console.WriteLine("SALARY : " + E.SALARY);
}
}
}
Output
ID : 101
NAME : Duggu Pandit
SALARY : 1000000