Showing posts with label C# 3.0. Show all posts
Showing posts with label C# 3.0. Show all posts

Friday, January 11, 2008

Properties in C#

Properties are a great way to define public get and/or set variables on your classes. With Visual Studio 2008 improvements have arrived to make working with properties even cleaner.

(If you don't know what properties are then I highly recommend you read Rajesh VS's post on c-sharpcorner for the basics)

Visual Studio 2005

Below is an example of a basic property.

Example:
private string _PackageName = string.Empty;
public string PackageName
{
    get { return _PackageName; }
    set { _PackageName = value; }
}

A nice feature added for .NET 2.0 is the ability to make one of the properties accessors private. For example here I will change the above codes SET accessir to make the setting only possible from inside of the class:

private set { _PackageName = value; }

Visual Studio 2008

In the next release of Visual Studio this is being enhanced even further by allowing something I like to call Short Properties (but the official name is Automatic Properties). This enhancement allows you to skip the body definition if all the code does is the basic SET/GET operation for a value. Here is an example:

Example:

public string PackageName { get; set; };

You can also use the private keyword in the same fashion to limit who can set the property vs. read the property:

public string PackageName { get; private set; };

In my opinion this syntax is much better in the majority of cases as it avoids having to define a private supporting variable and makes for neater and cleaner looking code.

Automatic Properties: C# 3.0 not .NET 3.0

Versions, acronyms, uhh ... confusion.

If anyone else is overloaded with technology like me you probably have suffered at one time or another from a mental block related to reading version numbers. The key to Automatic Properties is that its a C# 3.0 feature, not a .NET 3.0 feature. This is why it is only available with Orcas aka Visual Studio 2008, not as part of the .NET 3.0 extensions for 2005.

Acknowledgments: Special thanks to Jon Skeet for pointing these concepts out to me. I highly recommend everyone check out his new book called C# in Depth coming March 2008. (Click here to view the first chapter for free)