views:

260

answers:

2

When we define a property like

    public string Name {get; set;}

dot net can make our properties code. but when we use

    public string Name {get;}
    public string Name {set;}

we face with

'Hajloo.SomeThing.PropertyName.set' must declare a body because it is not marked abstract or extern. Automatically implemented properties must define both get and set accessors.

Actualy whay compiler can't determine the property and make code automatically ? what's happen ?

+1  A: 

If there is no setter, the property can never have anything other than the default value, so doesn't serve any purpose.

Joe
+3  A: 

Because the auto-implemented properties generate their own backing store for the property values. You have no access to the internal store.

Implementing a property with

  • just get : means you can only retrieve the values. You can't ever set the property value (even in the containing class)
  • just set : means you can only set the values. You can't retrieve the property value.

for a normal property

private int _data;
public int Data{  get { return _data } };

Here the parent class can do the following somewhere else in the class ( which it can't with auto props)

_data = 100;

Note: You can define an auto-prop like this (which is how I use it the most).

public int Data { get; private set;}

This means that the property can't be set by external clients of the class. However the containing class itself can set the property multiple times via this.Data = x; within the class definition.

Gishu
Might also be worth mentioning "private set" as a middle ground solution (and it may be what the OP is actually looking for"
Damien_The_Unbeliever
@Damien: That was eating at me too... laziness corrected.
Gishu

related questions