Properties in C#

Properties are similar to member variables in C#, however they differ in terms that they provide controlled access to member variables. Encapsulation is one of the pillars of object oriented programming and properties help implement encapsulation of member variables in C#. Consider a scenario where you want to store a value of 100 in an integer variable if the value is greater than 50, otherwise 0 should be stored in that particular variable. In such cases, instead of using a method, you can achieve the same functionality with the help of properties.

Properties have accessors in the form of get and set. The get accessor is used to return the value of the member field encapsulated by the property and the set accessor is used to set the value of the member field. Have a look at the following example to understand this concept.

´╗┐using System;

namespace CSharpTutorials {

    public class Vehicle {

        private string vehicle_name;
        private int vehicle_price;
        private int vehicle_model;

        public string Name {
            get {
                return vehicle_name;
            }
            set {
                vehicle_name = value;
            }
        }

        public int Price {
            get {
                return vehicle_price;
            }
            set {
                if (value > 50)  vehicle_price = 100;
                else  vehicle_price = 0;
            }
        }
		
        public int Model {
            get  {return vehicle_model;}
            set  {vehicle_model = value;}
        }
    }

    class Tutorial {
        static void Main(string[] args) {

            Vehicle vehicle = new Vehicle();
            vehicle.Price = 55;

            vehicle.Name = "BMW";
            vehicle.Model = 2005;
            Console.WriteLine(vehicle.Price);

            Console.ReadKey();
        }
    }
}

Download the code

In the above Example, a class named Vehicle has been defined that contains three member variables, vehicle_name, vehicle_price and vehicle_model. The class also contains three properties Price, Name and Model which are used for encapsulating vehicle_price, vehicle_name and vehicle_model,respectively.

A check has been implemented for the set accessor of the Price property which checks if the value being assigned to vehicle_price member variable is less than 50? If it is less than 50, 0 will be assigned to vehicle_price member, if the value is greater than 49, 100 will be assigned to it. In the Main method, 55 is being assigned to Price property. So now if the value vehicle_price variable is printed on screen, it will display 100.

<<< Events in C#Reflections in C# >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .