Properties in C#

Photo by Dan Burton on Unsplash

Properties in C#

Understanding encapsulation using properties

Exposing your class fields directly and making them accessible throughout your entire application can be problematic as it undermines your control over the values assigned or retrieved. In contrast, properties in C# provide a mechanism for encapsulation, which is a fundamental concept in Object-Oriented Programming (OOP). Properties enable you to address this issue by using set (write) and get (read) accessors to implement controlled access to fields.

A property with both set and get accessors offers both read and write capabilities, whereas a property with only a set accessor provides write-only access, and a property with only a get accessor provides read-only access. This encapsulation ensures that you can manage how data is modified and accessed within your class, promoting better code organization and maintainability.



public class Employee {
private int _id
private string _name
private int _salary


public int Salary{
get{
return this._salary
}
}

public string Name{

set{
if(string.IsNullorEmpty(value)){
throw new Exception "Name cannot be empty"
}
this._Name = value
}

get{
return string.IsNullorEmpty(this._name) ? "No Name Provided" : this._name
}
}

public int Id{
set{

(value <= 0){ // the value keyword 
throw new Exception("Employee Id should not be empty")
}this._id = value 
}
get{

return this.Id 

}

}

}

public class Program {

public static void Main(){
Employee E1 = new Employee();
E1._id = 200;
E1._name = "Wade"
Console.WriteLine("This is the Employee Id {0}, {1}": E1._id, E1._name )
}
}

Auto Implemented Properties
Auto-implemented properties offer a convenient way to reduce code repetition, especially when dealing with derived classes that involve straightforward value retrieval without complex logic. With auto-implemented properties, you can simply define the set and get accessors without explicitly declaring private fields, as the compiler handles this task automatically.



public class Employee {
private int _id
private string _name
private int _salary

public string _email{
set;
get;
}

public int _ssnit{
set;
get;
}

public int Salary{
get{
return this._salary
}
}

public string Name{
set{
if(string.IsNullorEmpty(value)){
throw new Exception "Name cannot be empty"
}
this._Name = value
}

get{
return string.IsNullorEmpty(this._name) ? "No Name Provided" : this._name
}
}

public int Id{
set{

(value <= 0){ // the value keyword 
throw new Exception("Employee Id should not be empty")
}this._id = value 
}
get{

return this.Id 

}

}

}

public class Program {

public static void Main(){
Employee E1 = new Employee();
E1._id = 200;
E1._name = "Wade"
Console.WriteLine("This is the Employee Id {0}, {1}": E1._id, E1._name )
}
}