Search This Blog

Friday, 20 July 2012

Properties


Properties allow you to control the accessibility of a classes variables, and is the recommended way to access variables from the outside in an object oriented programming language like C#.
A property is much like a combination of a variable and a method - it can't take any parameters, but you are able to process the value before it's assigned to our returned. A property consists of 2 parts, a get and a set method, wrapped inside the property: 

private string color;

public string Color
{
    get { return color; }
    set { color = value; }
}

Example:

class Program
    {
        public static void Main()
        {
            Car objcar = new Car();
            objcar.color = "Red";
            Console.WriteLine(objcar.describe());
            objcar.color = "Green";
            Console.WriteLine(objcar.describe());
            Console.ReadLine();
        }
    }
    class Car
    {
        private string colour;
       
        public string describe()
        {
            return "The colour of the Car is: " + color;
        }
        public string color
        {
            get { return colour; }
            set
            {
                if (value == "Green")
                {
                    colour = value.ToUpper();
                }
                else
                {
                    colour = value.ToLower();
                }
            }
        }
    }

Output:
The colour of the Car is: red
The colour of the Car is: GREEN

No comments:

Post a Comment