Using Reflection To Access Private Variables

If you ever decide you want to get sneaky and access a variable declared as private, you can use reflection to access the value. Here’s some sample code:


using System.Reflection;

public object GetPrivateVar()
{
    PrivateVarClass myPrivateVar = new PrivateVarClass ();
    object value = typeof(PrivateVarClass).InvokeMember ("thePrivateVar",
        BindingFlags.GetField |  BindingFlags.NonPublic | BindingFlags.Instance,
        null, myPrivateVar, null);
    return value;
}

Advertisements

About Ed Jones

Ed is a Connected Systems and .NET Specialist for RBA in the Twin Cities. Contact Ed

What do you think?

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

WordPress.com Logo

You are commenting using your WordPress.com 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

%d bloggers like this: