Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

Actually why the compiler can't determine the property and make code automatically? What's the problem?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
427 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...