Using reflection to invoke private methods

Here’s some sample code showing how you can do this; the example calls System::String::InternalLength which is private.

    BindingFlags::InvokeMethod |
    BindingFlags::NonPublic | BindingFlags::Instance,
    nullptr,gcnew String("hello world"),
    gcnew array<Object^>(0))));

Of course, in the above case what we did is not particularly useful since we could simply have used the Length property which internally calls InternalLength, but it’s just to show how it’s done 🙂


7 thoughts on “Using reflection to invoke private methods

  1. Hey Nish,

    C# code seems to be too simple and readable 🙂

    Console.WriteLine(typeof(String).InvokeMember("InternalLength", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance, null, "hello world", null));

  2. >>Access-modifier based security has no impact on Refelction
    hm, how can i secure my code in managed appl ?
    in unmanaged appl (binary) to invoke some method is not so easy, as it seams.
    in managed one even can generate il code into assembly, or maybe override some method\property – a good ‘platform’ for creating viruses… isn’t so ?

  3. Vlad, signing your .NET assembly can ensure your executable is the original; any tampering will change the key, which the CLR will recognize as changed, giving you security when you need it. 🙂

  4. Disagree with the C# comment. It is the style of original writing that is the cause for the confusion. Here is a modified C++/CLI statement of the same. 🙂

    Console::WriteLine(String::typeid->InvokeMember(“InternalLength”, BindingFlags::InvokeMethod | BindingFlags::NonPublic | BindingFlags::Instance, nullptr, “hello world”, nullptr));

    IMHO, the syntax is much the same in C++/CLI or C#, with the added power that is omnipresent in C++, whenever you need it.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s