Are immutable arrays possible in .NET?

后端 未结 9 821
忘了有多久
忘了有多久 2020-12-05 23:22

Is it possible to somehow mark a System.Array as immutable. When put behind a public-get/private-set they can\'t be added to, since it requires re-allocation a

9条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-05 23:52

    I believe best practice is to use IList rather than arrays in public APIs for this exact reason. readonly will prevent a member variable from being set outside of the constructor, but as you discovered, won't prevent people from assigning elements in the array.

    See Arrays Considered Somewhat Harmful for more information.

    Edit: Arrays can't be read only, but they can be converted to read-only IList implementations via Array.AsReadOnly() as @shahkalpesh points out.

提交回复
热议问题