Programming

Automatic Properties C#

[dropcap]A[/dropcap]utomatic properties used as a shorter way of defining a simple property which just sets and gets the value of a private member variable. Consider the following Code;

public class Point
 {
    private int _x, _y;
    public int X
    {
        get
        {
          return _x;
        }
        set
        {
          _x = value;
        }
    }
    public int Y
    {
        get
        {
          return _y;
        }
        set
        {
          _y = value;
        }
    }
}

The above code simply defining a class with basic properties. Now with the new C# compiler in Visual Studio .NET, we can write a shorter cleaner version using Automatic Properties which automatically generates the private fields with get/set operations :

public class Point
{
    public int X { get; set; }
    public int Y { get; set; }
}

The code above is even more readable and less verbose.
Note that this feature has nothing to do with LINQ. I just thought it would be appropriate to list it with the other new language features.

 

For more information see MSDN C# Programming Guide

Previous ArticleNext Article