Properties a short explanation using C#

less than 1 minute read

What are properties?

Properties are methods that protect access to class members.

  • Properties are class members that provide access to elements of an object or class.
  • Protect access to the state of object.
  • It likes fields, but they operate much like methods.
  • The get and set statements are called accessors.
  • Fields can’t be used in Interfaces so properties are the solution.

Syntax:

private double balance;
public double Balance
{
    get
    {
        return balance;
    }
    set
    {
        balance = value;
    }
}

Example:

public class Employee
{
    private double salary;
    private double taxRate = 0.05;
     
 
    public string Name { get; set; }
    public double YearOfExp { get; set; }
 
    public double YearlyMedicalAllowance {get; private set;}
 
    public Employee()
    {
        this.YearlyMedicalAllowance = 30000;
    }
 
    public double Salary
    {
        get { return salary; }
        set {
            if (value > 200000)
                salary = value - value * taxRate;
            else
                salary = 5000;
        }
    }
 
}

class Program
{
    static void Main(string[] args)
    {
        Employee objEmployee = new Employee();
        objEmployee.Name = "Rafiqul Islam";
        objEmployee.YearOfExp = 7;
        objEmployee.Salary = 5000;
         
        Console.WriteLine(objEmployee.Name);
        Console.WriteLine("Salary: " + objEmployee.Salary);
        Console.WriteLine("Yearly Madical Allowance" + objEmployee.YearlyMedicalAllowance);
 
        Console.ReadLine();
    }
}

Tags:

Categories:

Updated: