C# Automatic properties

Description

A property usually has a getter and/or setter that reads and writes to a private field of the same type as the property.

An automatic property declaration instructs the compiler to provide this implementation.

Compare the two versions of Rectangle class


class Rectangle{//from  ww  w .  j a  v a 2s. co m
   private int width;
   
   public int Width{
      get{
         return width;
      }
      set{
         width = value;
      }
   }
}

The following code creates an automatic property.


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

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

Syntax

We can redeclare the first example in this section as follows:


public class Person 
{ /*w  w w .  ja va 2s. c  o  m*/
   ... 
   public decimal Salary { get; set; } 
} 

The compiler automatically generates a private backing field of a compiler-generated name that cannot be referred to.

Example

The following code creates and accesses the automatic properties.


using System;//  w  w w  .  ja va 2s. c o m

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:





















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor