Skip to content
davidebbo edited this page Aug 10, 2011 · 2 revisions

ReflectionMagic

ReflectionMagic is a simple little framework that makes it a lot easier to do private reflection.

So suppose you have some assembly with classes that look like this:

public class Foo1 {
    private Foo2 GetOtherClass() { ... }
}

class Foo2 {
    private string SomeProp { get { ... } }
}

And say you have an instance foo1 of the public class Foo1 and you want to call the private method GetOtherClass() and then get the SomeProp property off of that.

Using traditional private reflection, you would write something like this:

object foo2 = typeof(Foo1).InvokeMember(
    "GetOtherClass",
    BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.InvokeMethod,
    null, foo1, null);
PropertyInfo propInfo = foo2.GetType().GetProperty(
    "SomeProp",
    BindingFlags.Instance | BindingFlags.NonPublic);
string val = (string)propInfo.GetValue(foo2, null);

But if you instead use ReflectionMagic, you can just write:

string val = foo1.AsDynamic().GetOtherClass().SomeProp;

Get it via NuGet

The easiest way to get ReflectionMagic is to install it via NuGet.

When would you want to use this

Clearly, in most cases it's not a great idea to start poking into internals for the sake of it. But it might make sense to do it in a few cases:

  • To unit test some code that's not public and that can't easily make you 'friend'
  • To just quickly try some things out

The purpose of this framework is not to encourage anyone to use private reflection in situations where you would not have done it anyway. Instead, the purpose is to show you how to do it much more easily if you decide that you need to use it. Putting it a different way, I’m not telling you to break the law, but I’m telling you how to break the law more efficiently if that’s what you're into! :)

What about medium trust

Private reflection is often not possible when running in medium trust, and ReflectionMagic has the same restrictions. This is not about bypassing some security, but only about sugar coating the syntax.

Project history

This started with a Blog post that I wrote quite a while ago. For the most part, the code has been dormant, and I just wanted to get it out there.