Properties a short explanation using C#

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();
        }
    }
Please share, if it is helpfulShare on FacebookShare on LinkedInTweet about this on TwitterShare on Google+Email this to someonePrint this page

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>