简体   繁体   中英

Why property is public and the setter is private

I saw this example on some website:

public class infoData
{
    public FridgeProduct fridgeProduct { get; private set; }
}

What is the point to do private setter if fridgeProduct field is defined as public and can be accessed by definition from any other class?

The private setter has the effect that the property can be written to only from within the class, not from outside.

Note that the access specification (private) on the set accessor overrides the access specification (public) of the property. As Aluan Haddad noted in the comments, the compiler enforces that the accessibility of an individual accessor cannot be less restrictive than the accessibility of the property itself.

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