/* Code Musings */

Breaking Encapsulation Using Reflection

In C++, encapsulation meant that all private or protected elements of a class were unreachable by regular means of access (Ignoring dirty tactics like pointer manipulation to gain access to member variables). Not so with C#. To my surprise, I found that you could manipulate public properties even when they are parked as ‘private set’.

At first, I thought it was a bug in the code. Somewhere, I had a brain-fart and accidentally forgot to make the property’s setter private. Nope. As it turned out, my code was correctly decorated with the private keyword.

Moving on, I decided to inspect the code that consumes this class. It uses reflection to iterate through the properties and extract the ‘DialogControl’ attribute. Attributes are a wonderful invention, that allow me to parse a class and determine what use I have for a given member variable. But in this case, it confused me.

My reflection code is nothing interesting. After pulling out the property, and prompting the user for input, it attempts to apply the value back into the property.

Everything works well, which is the concerning thing. The call to SetValue ignores the fact that the setter is marked as private and sets the value regardless. The only work around I see to this, is that if you extrapolate your properties into an interface, you can exclude the set keyword entirely and generate an exception during the SetValue call.

This post seems to explain that it is possible and people know about it. What bugs me is that I cannot find out WHY this is allowed. Until I do, I’ll just add it to the ever-growing list of things that irk me about C#.

Leave a Reply