Automatic property

The get and set accessors' logic can be added by C# compiler.

This kind of property is called Automatic property.

Compare the two versions of Rectangle class


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

class Rectangle{
   public int Width {get; set;}
}

C# will generate the backend private field which is used to hold the value of width.

The following code creates and accesses the automatic properties.


using System;

public class MainClass
{
    static string MyStaticProperty
    {
        get;
        set;
    }

    static int MyStaticIntProperty
    {
        get;
        set;
    }

    static void Main(string[] args)
    {
        // Write out the default values. 
        Console.WriteLine("Default property values");
        Console.WriteLine("Default string property value: {0}", MyStaticProperty);
        Console.WriteLine("Default int property value: {0}", MyStaticIntProperty);

        // Set the property values. 
        MyStaticProperty = "Hello, World";
        MyStaticIntProperty = 32;

        // Write out the changed values. 
        Console.WriteLine("\nProperty values");
        Console.WriteLine("String property value: {0}", MyStaticProperty);
        Console.WriteLine("Int property value: {0}", MyStaticIntProperty);

    }
}

The output:


Default property values
Default string property value: 
Default int property value: 0

Property values
String property value: Hello, World
Int property value: 32
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.