'C# - How to guarantee that a properties remains Get only over time?

I'm implementing a piece of sensitive software and I can see a possible "failure point"/"security leak" IF in the future someone sticks a public set on a specific property.

Besides the obvious //Do not make this property set operator public because of XYZ are there other safeguards I can put in place to prevent such misguided change?



Solution 1:[1]

I don't know your exact design but as I understand from the comments, you're using property to return a resource that needs to be discarded properly with using. If somebody else sets the property the handle to the IDispoable is lost, so it's up to the GC's mercy to dispose it.

Don't use properties to return IDisposable's (or any other resource type hat needs to be explicitly disposed). Use a method instead. That way, the object reference wouldn't be cached in the class, but in the caller. So, caller would be responsible of disposing it. This prevents adding any other code to change the instance in your class, because caching isn't done there anymore.

You can only direct developers to the right direction with a design that describes its intent clearly.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1