Const correctness in C# with rich types

我的未来我决定 提交于 2019-12-05 03:21:35

Can you get immutability in C#? Sure, if you design for it. You can do creative things with interfaces, and so on, to only expose the get of properties and none of the mutable methods.

That said, keep in mind there is nothing that prevents a crafty user from casting it back to the actual type (of course, same could be said of C++, you can cast away const-ness).

ISomeReadOnlyInterface readOnly = new SomeFullObject();

// hah, take that read-only interface!
((SomeFullObject)readOnly).SomeMutatingMethod();

Same with collections. Even if you return a ReadOnlyCollection (which prevents mutating behaviors on the collection itself) the data in the collection is still mutable (as long as the type allows it of course).

So I'm afraid there's really no simple answer here. There's no "flip-a-switch" const that gives you what C++ does.

It's really up to you, you can:

  • Design your types to be immutable and return iterators (or other read only sequences) instead of mutable collections.
  • Return new copies each time so that if they alter them it's no biggie.
  • Just return the actual data and leave tampering behavior as "undefined".
  • etc...

The latter is what collections like Dictionary<TKey, TValue> do. There's nothing that says you can't make the key type a mutable type (but woe if you do), and the MSDN is pretty clear that if you alter the key in such a way that it's hash code changes, it's on your own neck...

For my own work, I tend to keep it simple unless there is actually a big concern my class may be altered in a way that would cause side-effects. For example, if I'm storing web service results in a cache, I'll return a copy of the cached item instead so that if a user modifies the result they won't inadvertently modify the cached value.

So, long and the short of it is that I wouldn't worry about const-correctness of every type you return, that's just way too much. I'd only worry about things that you return that, if altered, could create a side-effect to other users.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!