Hack .NET Framework : Use private classes to fulfill your need
September 26, 2007
Lutz Roeder's Reflector is the most useful .NET utility ever built. It has helped me many times in the past to browse through compiled code and use it correctly. Since it decompiles the code and shows the code inside, it is actually better than help files or any other form of documentation on any assembly. If you use the Reflector then you can find that .NET framework itself has many private utility classes built into it which are used by the public classes but as a developer we cannot use it. Reflector will let you find a lot of those classes which can be instantiated and used via Reflection.
Lets take the example of System.Security.Util is a private namespace in mscorlib which has a class called Hex. This class can encode and decode hexadecimal string. Since it is a reusable class we should use it when required rather than writing a new class. See the Hex class below in Reflector
Now this looks like a pretty useful class. But its private, how do we use it? In order to do so we can get hold of the private type via reflection like this:
Type type = Type.GetType("System.Security.Util.Hex, mscorlib");
Then we need to get a hold of the method ( in this case the class is static so are its method ).
MethodInfo encodeHexString = type.GetMethod("EncodeHexString", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
We now have the method and all we need to do is to invoke it. Since the method is static it will not need any object as reference when invoked.
List<object> parms = new List<object>();
parms.Add( Encoding.ASCII.GetBytes("This is to be converted to hex"));
string encoded = (string)encodeHexString.Invoke(null, parms.ToArray());
Here we have invoked the method of a private class in an assembly and got output from it. Ain't that nice!
In order to make things simpler you can write a wrapper class around and use it to instantiate and call the private classes or private methods of any class.
This sample contains such a class and here is how easy it is to use it. In the next code block we are converting a string to hexadecimal format and then getting it back to original format using the private Hex class.
HiddenType wrapper = new HiddenType("System.Security.Util.Hex,mscorlib");
string originalString = "This is a string";
Console.WriteLine("Original string is \t: {0}", originalString);
byte[] bytes = Encoding.ASCII.GetBytes (originalString);
string encodedString = (string) wrapper.InvokeStaticFunction("EncodeHexString", bytes);
Console.WriteLine("Encoded string is \t: {0}", encodedString);
byte[] decodedBytes = (byte[]) wrapper.InvokeStaticFunction("DecodeHexString", encodedString);
string decodedString = Encoding.ASCII.GetString(decodedBytes);
Console.WriteLine("Decoded string is \t: {0}", decodedString);
The code sample can be downloaded below. Keep on reflecting ...