Fast dynamic wrapper for accessing hidden methods and fields of .Net objects. Uses 4.0 dynamic feature to allow seamless access to non-public object members. Facilitates white-box unit testing, exposes APIs that should be public and allows construction of elaborate hacks. Should not kill your cat provided you are careful. Available on NuGet.
Handling private instance methods, fields and properties on a visible type:
// create an Exposed instance from a ClassWithHiddenMethods instancedynamicexposed=Exposed.From(newClassWithHiddenMethods());// calling a private methodstringpassword=exposed.GeneratePassword(8);// reading a private fieldintprivateFieldValue=exposed.internalCount;// setting a private fieldexposed.internalCount=privateFieldValue*2;// reading a protected propertycharprotectedPropertyValue=exposed.InternalData;Accessing private field on a hidden type:
// get the Type via reflectionTypehiddenClass=Type.GetType("TestSubjects.HiddenClass, TestSubjects");// call the parameterless constructor of a hidden typedynamicexposed=Exposed.New(hiddenClass);stringpassword=exposed.password;Accessing internal static method from type:
dynamicexposed=Exposed.From(typeof(ClassWithInternalStaticMethod));decimalconvertValue=exposed.ConvertValue(8);- performance assessment (binding restrictions vs caching, compare with CreateDelegate solution)
- generic methods (there are tests for them, some suggested solutions on StackOverflow )
- constructors (currently
Exposed.New()delegates toActivator.CreateInstance())
- Bug squash: Testing private methods with C# 4.0 - starting idea
- Igor Ostrovsky: Use C# dynamic typing to conveniently access internals of an object - convenient API
- Miguel de Icaza: C# 4's Dynamic in Mono - performant dynamic object implementation using
GetMetaObject()