开发者

Auto-implemented get/set properties

开发者 https://www.devze.com 2023-02-28 07:47 出处:网络
Is there any downside to letting C# create the private backing fields that are generated by using the automatic property crea开发者_开发知识库tion (ie {get; set})?

Is there any downside to letting C# create the private backing fields that are generated by using the automatic property crea开发者_开发知识库tion (ie {get; set})?

I am aware that it is automatic and therefore you cannot customize the get/set, and would like to know if there are any other implications.

Thanks!


The biggest issue that I have come across is that it is often very limiting when looking at binding scenarios. Typically when using data binding you need to implement INotifyPropertyChanged which is not supported by the automatic properties.


If you are using BinaryFormatter, changing to (or from) automatically implemented properties is a breaking change, since field names matter to BF. Of course, one easy fix there is: don't use BF!

You also can't add attributes to the backing field using automatic properties.

No field initialisers.

No true readonly for use with immutability.

You can't add logic, obviously; no laziness, validation, side-effects or notification events.

With structs, you need to call :this() on custom constructors, which is ugly.

Otherwise though: they are great. I'm a big fan.


The biggest problem is that you can't work with the backing fields, since they are created by the compiler. This means you can't declare them const or readonly, it means you can't add logic around accessing them (lazy initialization, for example), etc. The good news is that starting with the autoproperty makes the refactor to using a backing field easy, when you have a reason.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号