The C# 2008 supports number of new constructs such as lambda expression, automatic properties, implicitly typed local variables, partial methods etc. Let’s examine automatic properties.

Up till now we have been encapsulating our private fields as

class TestClass
private string name;
public string Name
get { return name; }
set { name = value; }


This approach is good enough but let say if we require 20 fields as public interface then it requires a little effort of creating private field first and then encapsulating it as a public property.

As the word “automatic” refers, you can now create just properties and C# will automatically create a backing private field for you at compile time though it’s not visible to you.

class TestClass
public string Name { get; set; }

The automatic properties are initialized by default values i.e. integers are initialized with zero, strings with empty, reference type with null etc.

You can apply restricting access similarly as one can apply on normal properties such as

public string Address { get; private set; }

having public scope of get and private scope of set. However you cannot write read only fields as you previously like

public string Address { get; } //error

read only should be done by restricting access through access modifiers. We will access the automatic properties in the similar way as we did in case of normal properties.

TestClass tc = new TestClass();
tc.Name = “CD”;


The automatic properties are one of the good extensions C# 2008 provides, if you are just need a simple public property to access private fields outside class then automatic properties are the good alternative.

Categories: C#


Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *