简体   繁体   中英

Auto-implemented get/set properties

Is there any downside to letting C# create the private backing fields that are generated by using the automatic property creation (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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM