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

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

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

1 Answer

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.


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