Define a real read-only list in C #

Source: Internet
Author: User

The readonly keyword in C # indicates that fields in the class can only be initialized during definition or in the constructor. Normal data can achieve the expected results, but in the object or list, to achieve the read-only effect, only one readonly keyword is not allowed. When you modify a list with readonly, you can still use the add and remove methods in other classes to change it. However, the read-only attribute you want may be:Only items in this list can be modified in the current class!

The following example shows a list modified with the readonly keyword. Its content items can still be added or deleted in other classes:


Even if it is encapsulated as a read-only attribute, you can still operate in other classes:


However, you can change the attribute type to ienumerable <t> to achieve the desired effect. Because the ienumerable <t> class does not have the add and remove methods, the list <t> class inherits the ienumerable <t> class, And the add and remove methods added to the List <t> class are as follows:


If you want to create a fully read-only attribute, you can use readonlycollection even if it cannot be modified in the current class. <t>:


In. Net 4.5, list <t> inherits ireadonlylist <t> and ireadonlycollection <t>, giving us a simpler way of writing, which can also achieve the above results:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.