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
235 views
in Technique[技术] by (71.8m points)

.net - Are C# properties actually Methods?

Till now, I was under the impression that Properties & Methods are two different things in C#. But then I did something like below.

enter image description here

and this was an "Eye Opener" to me. I was expecting one property stringProp and one method stringProp but instead I got this.

Why this happened? can someone explain please.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Yes, the compiler generates a pair of get and set methods for a property, plus a private backing field for an auto-implemented property.

public int Age {get; set;}

becomes the equivalent of:

private int <Age>k__BackingField;

public int get_Age()
{
     return <Age>k__BackingField;
}

public void set_Age(int age)
{
    <Age>k__BackingField = age;
}

Code that accesses your property will be compiled to call one of these two methods. This is exactly one of the reasons why changing a public field to be a public property is a breaking change.

See Jon Skeet's Why Properties Matter.


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

...