Because sometimes, I really need a friend.
I can think of the following tricks:
- Read only wrapper - like ReadOnlyCollection. The friend keeps the pointer to the modifiable object, while everyone else can access only the wrapper.
- Write delegate - the friend gives the constructor of the object a reference to a delegate as one of the parameters, the constructor fills it with an address to a private method that can be used to modify the object.
- Reflection - obviously a bad idea. Included for completeness.
- Multiple assemblies - put your friends together in a separate assembly and set your modifier methods
internal
. - Expose the modifiable object, but add comments to modifier methods "This is an infrastructure method - don't call it!"
- Nested classes.
- Add
System.ComponentModel.EditorBrowsable(System.ComponentModel. EditorBrowsableState.Never)
attribute to the member you want only the friend to access to hide it from IntelliSense. - Implicit interface implementation - see comments.
Is this list exhaustive? Can anyone sort these in order of decreasing performance? Order of decreasing neatness? Any suggestions when to use which?