public class Demo
{
private List<string> _items;
private List<string> Items
{
get
{
if (_items == null)
_items = ExpensiveOperation();
return _items;
}
}
}
Other methods in the Demo class will have access to the _items field. Since I’m using a property to lazy load the items, I do not want another developer to mistakenly try to use the _items field.
I know there is the ObsoleteAttribute that I may use, but this field isn’t technically obsolete.
Is there a better way to mark a member as “do not use”?
Though it’s not a general technique for what you want to do (and there isn’t one and, as the other answers cover, you need to trust other devs), in this instance, you could create a
Lazy<List<T>>(assuming .NET 4 or later – though it’s easy to backport)The
readonly/ non-mutable approach is generally the way to go for backing fields either way.EDIT: Based on @Timwi’s answer (go +1 if you like the idea) one can go to town on it, and in a JavaScript stylee use capability-based restriction to not even expose the
Lazyfield, just an operation closed over it (Also incorporates @Mr Disappointment’sReadOnlyCollectionsuggestion):And thus endeth our stupid coding tricks post.