Monday, June 4, 2012

Collection properties should be read-only, C#

It is recommended that your collection property should be read only i.e. they should not contain setter. A writable collection property allows a user to replace the collection with a completely different collection. A read-only property stops the collection from being replaced but still allows the individual members to be modified.

If you actually want to replace the collection then the preferred design pattern is to include a method to remove all the elements from the collection and a method to re-populate the collection. Instead of setter property use Clear and Add methods of collection in order to replace the complete collection.

This error is reported by code validation tools like FxCop.

Sources: MSDN Collection properties should be readonly.

No comments:

Post a Comment