On reflection: making use of internal system classes
August 7, 2006 | 7:16 PM | Comments (0) | Post comment
It is commonly known that reflection is a powerhouse. And as every raw power it has to be treated with extra care (e.g. reflection easily breaks the encapsulation.) A point that is often overlooked is that one can access private and internal methods (classes, etc.) via reflection mechanism. This technique, which essentially relies on the late binding, depends on the fact that one knows the name of the entity to access. Unless the developer has a full control over the private member it is very dangerous to assume that its name is going to stay. For example, obfuscation would break the code that blindly relies on the naming of the private members. However, there are situations when such a technique can be extremely useful.
One thing that I absolutely love about the .NET Framework libraries is that these are not obfuscated. The one thing I hate is that some of very useful classes are made internal. Reflection to the rescue! Names of classes in system libraries are set in stone (at least between major releases) and, hence, make a perfect target for reflecting upon.
.NET libraries themselves utilize reflection a lot. Equipped with this knowledge you can do some magic tricks. For example, EditorAttribute accepts a string with the name of the editor class. Naturally reflection is going to be used behind the scene to instantiate an editor. What does it give us? Well, it suggests that you can use all those fancy internal editors, like ImageIndexEditor. All you have to do is to specify the name of the class (optionally the full name including the assembly) and let the reflection do the rest.
[Editor("System.Windows.Forms.Design.ImageIndexEditor",
typeof(UITypeEditor))]
public int ImageIndex { ... }
mindon.net