Make a field accessible to ONLY its corresponding property?
.net, c#
Solution
There is nothing in C# that can help you hide `private` field from members of the same class.
Your options:
- some post-processing (i.e. custom plugin for code analysis with FxCop)
- move this fields/properties into base class and mark fields `private`. Than add real code to derived class - so derived class will not be able to reach fields
- use containment with interfaces instead.
Side note: you'll not be able to hide fields from reflection...
Problem
Say we have a private backing field and a private property exposing that field. Does C# support attributes or any other syntax to force a compiler error if any code, even code inside the class, attempts to access or modify the field except for the property without encapsulating the field and property in their own object? Please see a simple example below. ``` /// <summary> /// Class to cache and quickly access data. Please only use this class if 1) the data to be cached uses little memory and 2) the number of DB reads is high and could cause a performance strain. /// </summary> class BMIDataCache { #region fields protected static BMITimedDictionary<String, Device> _devices; #endregion #region properties protected static BMITimedDictionary<String, Device> Devices { get { if (_devices == null) { _devices = new BMITimedDictionary<String, Device>(); //Do some other stuff later. } return _devices; } set { _devices = value; } } public void Test1() { //Inside this method, trying to access _devices will cause a compiler error, but not Devices } } ```