Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
431 views
in Technique[技术] by (71.8m points)

c# - Why Automatically implemented properties must define both get and set accessors

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...