views:

184

answers:

4

Before C# 3.0 we done like this:

class SampleClass
{
   private int field;
   public int Property { get { return this.field } set { this.field = value } }
}

Now we do this:

class SampleClass
{
   public int Property { get; set; }
}

(Look ma! no fields!) Now if I want to customize the Getter or the Setter, the field must be explicit as it was in C#2.0?

+7  A: 

Yes, that's the only way. No shortcut for customization (other than access modifiers).

Mehrdad Afshari
+1  A: 

Yeah, the purpose of the automatic properties is provide a means to add customizations in the future, without affecting existing users of the class. This usually means adding a private/protected backing field.

Andy White
Generally, all fields should be private for good encapsulation. If you want subtypes to access the field you should have a public getter and protected setter (or variants thereof)
thecoop
+2  A: 

With C# 3.0 and automatic properties, you can still change the access levels:

class SampleClass
{
   public int Property { get; private set; }
}
Andrew Robinson
A: 

You also cannot specify readonly fields using automatic properties, nor can you use variable initializers (although I have seen a few suggested language extensions that would allow those).

You can make automatic properties virtual, but that means that any access to the property in the class could call subtype implementations instead.

thecoop