How to do encapsulation in C# Console Application | Object Oriented Programming Tutorial



namespace FistConsoleProject;

public class Student
{
//This is encapsulation 🙂
//Now outside of the class we dont have any get id set id anything like that

//Encapsulation is Hiding the Complexity

private int _id;
private string _name;
//prop is short cut to generate get and set
public int Id { get; set; }

public string Name { get; set; }
//we call this as properties, properties comes from encapsulation, we can use this if there are no conditions like below

// private int _mark;
//Using Set and Get method to encapuslate the id class field, as a result we can have better control
//outside of the class for class memebers
//this is how to do encapsulation using Get and Set
//now when its come to big classes Get and Set might be hard
//but our ambission is control inputs, name should not be null, id should not be less than zero
// we call Get and set as accessors

//let’s go ahead and see how to write these code in meaningful manner

// public void SetName(string Name)
// {
// if (string.IsNullOrEmpty(Name))
// {
// throw new Exception(“Student name cannot be null”);
// }
//
// _name = Name;
// }
//
// public string GetName()
// {
// return _name;
// }

// public string Name
// {
// set
// {
// if (string.IsNullOrEmpty(value))
// {
// throw new Exception(“Student name cannot be null”);
// }
//
// _name = value;
// }
// get
// {
// return _name;
// }
// }

// public void SetId(int Id)
// {
// if (Id is less than symbol = 0)
// {
// throw new Exception(“Student id should be greater than 0”);
// }
//
// _id = Id;
// }

// public int Id
// {
// set //we call get and set as accessors
//
// {
// if (value is less than symbool= 0)
// {
// throw new Exception(“Student id should be greater than 0”);
// }
//
// _id = value;
// }
// get //we call get and set as accessors
// {
// return _id;
// }
// }
// public int GetId()
// {
// return _id;
// }
}

using FistConsoleProject;

var student = new Student();
student.Id = 101;
student.Name = “John”;
//student._mark = -90;
//now we have controls
Console.WriteLine(“ID = {0} & Name = {1} “, student.Id, student.Name);

//here what we have done is controlling inputs
//Using Set and Get method to encapuslate the id class field

//here if you feel any complexsity?
//dont worry c# support more easiy way