Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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

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

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top