Export (0) Print
Expand All
375 out of 478 rated this helpful - Rate this topic

Properties Tutorial

Visual Studio .NET 2003

This tutorial shows how properties are an integral part of the C# programming language. It demonstrates how properties are declared and used.

Sample Files

See Properties Sample to download and build the sample files discussed in this tutorial.

Further Reading

Tutorial

This tutorial includes two examples. The first example shows how to declare and use read/write properties. The second example demonstrates abstract properties and shows how to override these properties in subclasses.

Example 1

This sample shows a Person class that has two properties: Name (string) and Age (int). Both properties are read/write.

// person.cs
using System;
class Person
{
    private string myName ="N/A";
    private int myAge = 0;

    // Declare a Name property of type string:
    public string Name
    {
        get 
        {
           return myName; 
        }
        set 
        {
           myName = value; 
        }
    }

    // Declare an Age property of type int:
    public int Age
    {
        get 
        { 
           return myAge; 
        }
        set 
        { 
           myAge = value; 
        }
    }

    public override string ToString()
    {
        return "Name = " + Name + ", Age = " + Age;
    }

    public static void Main()
    {
        Console.WriteLine("Simple Properties");

        // Create a new Person object:
        Person person = new Person();

        // Print out the name and the age associated with the person:
        Console.WriteLine("Person details - {0}", person);

        // Set some values on the person object:
        person.Name = "Joe";
        person.Age = 99;
        Console.WriteLine("Person details - {0}", person);

        // Increment the Age property:
        person.Age += 1;
        Console.WriteLine("Person details - {0}", person);
    }
}

Output

Simple Properties
Person details - Name = N/A, Age = 0
Person details - Name = Joe, Age = 99
Person details - Name = Joe, Age = 100

Code Discussion

  • Notice the way that the properties are declared, for example, consider the Name property:
    public string Name
    {
        get 
        {
           return myName; 
        }
        set 
        { 
           myName = value; 
        }
    }
    

    The Set and Get methods of a property are contained inside the property declaration. You can control whether a property is read/write, read-only, or write-only by controlling whether a Get or Set method is included.

  • Once the properties are declared, they can be used as if they were fields of the class. This allows for a very natural syntax when both getting and setting the value of a property, as in the following statements:
    person.Name = "Joe";
    person.Age = 99;
    
  • Note that in a property Set method a special value variable is available. This variable contains the value that the user specified, for example:
    myName = value; 
    
  • Notice the clean syntax for incrementing the Age property on a Person object:
    person.Age += 1;
    

    If separate Set and Get methods were used to model properties, the equivalent code might look like this:

    person.SetAge(person.GetAge() + 1);
    
  • The ToString method is overridden in this example:
    public override string ToString()
    {
        return "Name = " + Name + ", Age = " + Age;
    }
    

    Notice that ToString is not explicitly used in the program. It is invoked by default by the WriteLine calls.

Example 2

The following example shows how to define abstract properties. An abstract property declaration does not provide an implementation of the property accessors. The example demonstrates how to override these properties in subclasses.

This sample consists of three files. In the Properties Sample, these files are compiled into a single compilation but in this tutorial, each file is compiled individually and its resulting assembly referenced by the next compilation:

  • abstractshape.cs: The Shape class that contains an abstract Area property.
  • shapes.cs: The subclasses of the Shape class.
  • shapetest.cs: A test program to display the areas of some Shape-derived objects.

To compile the example, use the command line:

csc abstractshape.cs shapes.cs shapetest.cs

This will create the executable file shapetest.exe.

File 1 - abstractshape.cs

This file declares the Shape class that contains the Area property of the type double

// abstractshape.cs
// compile with: /target:library
// csc /target:library abstractshape.cs
using System;

public abstract class Shape
{
   private string myId;

   public Shape(string s)
   {
      Id = s;   // calling the set accessor of the Id property
   }

   public string Id
   {
      get 
      {
         return myId;
      }

      set
      {
         myId = value;
      }
   }

   // Area is a read-only property - only a get accessor is needed:
   public abstract double Area
   {
      get;
   }

   public override string ToString()
   {
      return Id + " Area = " + string.Format("{0:F2}",Area);
   }
}

Code Discussion

  • Modifiers on the property are placed on the property declaration itself, for example:
    public abstract double Area
    
  • When declaring an abstract property (such as Area in this example), you simply indicate what property accessors are available, but do not implement them. In this example, only a Get accessor is available, so the property is read-only.

File 2 - shapes.cs

The following code shows three subclasses of Shape and how they override the Area property to provide their own implementation.

// shapes.cs
// compile with: /target:library /reference:abstractshape.dll
public class Square : Shape
{
   private int mySide;

   public Square(int side, string id) : base(id)
   {
      mySide = side;
   }

   public override double Area
   {
      get
      {
         // Given the side, return the area of a square:
         return mySide * mySide;
      }
   }
}

public class Circle : Shape
{
   private int myRadius;

   public Circle(int radius, string id) : base(id)
   {
      myRadius = radius;
   }

   public override double Area
   {
      get
      {
         // Given the radius, return the area of a circle:
         return myRadius * myRadius * System.Math.PI;
      }
   }
}

public class Rectangle : Shape
{
   private int myWidth;
   private int myHeight;

   public Rectangle(int width, int height, string id) : base(id)
   {
      myWidth  = width;
      myHeight = height;
   }

   public override double Area
   {
      get
      {
         // Given the width and height, return the area of a rectangle:
         return myWidth * myHeight;
      }
   }
}

File 3 - shapetest.cs

The following code shows a test program that creates a number of Shape-derived objects and prints out their areas.

// shapetest.cs
// compile with: /reference:abstractshape.dll;shapes.dll
public class TestClass
{
   public static void Main()
   {
      Shape[] shapes =
         {
            new Square(5, "Square #1"),
            new Circle(3, "Circle #1"),
            new Rectangle( 4, 5, "Rectangle #1")
         };
      
      System.Console.WriteLine("Shapes Collection");
      foreach(Shape s in shapes)
      {
         System.Console.WriteLine(s);
      }
         
   }
}

Output

Shapes Collection
Square #1 Area = 25.00
Circle #1 Area = 28.27
Rectangle #1 Area = 20.00

See Also

C# Tutorials

Show:
© 2014 Microsoft. All rights reserved.