C# getters, setters declaration [duplicate]

≯℡__Kan透↙ 提交于 2019-11-27 22:54:16

Differences:

  • The second form will only compile with a C# 3 compiler or later
  • The second form doesn't let any code (even in the same class) access the field directly, as the real field has an "unspeakable name"

The second version is what's known as an automatically implemented property (or "automatic property" for short). They were introduced in C# 3. If you're only writing code which looks like the first version - i.e. there's no logic involved - then automatic properties are great. You can always add logic later by converting it into the first form. All your code will be compatible with that change, in both source and binary compatibility terms.

Be aware that automatic properties don't allow you to specify default values, and there's no such thing as a genuinely readonly automatic property (i.e. one without a getter). The closest you can come is a public getter with a private setter, e.g.

public string Name { get; private set; }

It's not quite the same, but it's close enough in many situations.

The first is a standard property. You must define a field to store the value in. The second is an auto-implemented property, only availible in C# 3.0 and later.

The answer is in the IL. Use ildasm and compare.

http://msdn.microsoft.com/en-us/library/f7dy01k1%28v=VS.90%29.aspx

Ultimately, it works out to the same thing in this instance. The difference comes when you want to apply any rules to the getting/setting, in which case you need to use the private/protected variable and hide it behind a public property.

Alexander Vakrilov

No. Actually, when you use the shorter version (public string Name { get; set; }) the compiler automatically generates a private field for the property.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!