Properties

Properties are fields with logics.

C# uses get and set keywords to declare a property.


using System;
class Rectangle{
   private int width;
   
   public int Width{
      get{
         return width;
      }
      set{
         width = value;
      }
   }
}

class Program
{
    static void Main(string[] args)
    {
        Rectangle r = new Rectangle();
        r.Width = 5;
        Console.WriteLine(r.Width);
    }
}

The output:


5

get and set are called property accessors.

get accessor is called when reading the property and set accessor is called when assigning value to the property.

value is the parameter, which designates the value being assgined.

A property can have the following modifier:

java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.