In this example we use the SetId(Int Id) and GetId() methods to encapsulate _id class field
As a result, we have better control on what gets assigned and returned from the _id field.
Note: Encapsulation is one of the primary pillars of object oriented programming.
PROPERTIES:
===========================
In C# we use set and get properties
Read/Write properties
Read Only Properties
Write Only Properties
Auto Implemented Properties
properties
1. we use get and set accessors to implement properties
2. A property with both get and set accessor is a Read/Write property
3. A property with only get accessor is a Read Only property.
4. A property with only set accessor is a Write only property
Note: The advantage of properties over traditional Get() and Set() methods is that, you can access them as if they were public fields.
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ConsoleApplication4;
namespace ConsoleApplication4
{
public class Student
{
private int _Id;
private string _Name;
private int _PassMark = 35;
private string _City;
private string _Email;
public string Email { get; set; }
//get // when there is no logic then we can simply write like above.
//{
// return this._Email;
//}
//set
//{
// this._Email = value;
//}
public string city
{
get
{
return this._City;
}
set
{
this._City = value;
}
}
public int PassMark
{
get
{
return this._PassMark;
}
}
public string Name
{
set{
if (string.IsNullOrEmpty(value))
{
throw new Exception(“NAME SHOULD NOT BE EMPTY OR NULL”);
}
this._Name = value;
}
get
{
return string.IsNullOrEmpty(this._Name) ? “No Name” : this._Name;
}
}
public int Id
{
set
{
if (value <= 0)
{
throw new Exception(“student id is not negative value”);
}
this._Id = value;
}
get
{
return this._Id;
}
}
}
public class Program
{
static void Main()
{
Student C1 = new Student();
C1.Id =101;
C1.Name = “malla”;
Console.WriteLine(“student id = {0}”, C1.Id);
Console.WriteLine(“student Name = {0}”, C1.Name);
Console.WriteLine(“student PassMark = {0}”, C1.PassMark);
Console.ReadLine();
}
}
}
———————————-