An interesting question arose today of how to get/change encapsulated (Private) variable value from the Static class dynamically.

It is easy to imagine why this would be useful. You might want to read initial values from standard or third party DLLs, and modify it for customization.

Using Reflection is the feature in .Net, which enables us to get some information about object in runtime. That information contains data of the class. Also it can get the names of the methods that are inside the class and constructors of that object.

// Loads an assembly using its file name

Assembly assemblyInformation = Assembly.LoadFrom("MyNamespace.DLL");

 

// Fetch the types available in the assembly

Type[] assemblyTypeInformation = assemblyInformation.GetTypes();

 

foreach (Type TypeInformation in assemblyTypeInformation)

{

   Console.WriteLine(TypeInformation.FullName);

   PropertyInfo[] propertyInfos;

   propertyInfos = TypeInformation.GetProperties(BindingFlags.Public |

                                                                  BindingFlags.Static);

  // write property names

   foreach (PropertyInfo propertyInfo in propertyInfos)

   {

      Console.WriteLine(propertyInfo.Name);

   }

   FieldInfo[] fieldInfos;

   fieldInfos = TypeInformation.GetFields(BindingFlags.NonPublic |

                                                                  BindingFlags.Static);

   // write Hidding variable names

   foreach (FieldInfo fieldInfo in fieldInfos)

   {

      Console.WriteLine(fieldInfo.Name);

   }

 

}

The first thing to notice about the static class is that it not allows creating its own. It loaded automatically when main assembly access first time. If we try to load DLL using file, it will create another instance of class and running independently with current assembly reference. This will not solve our perpose.

The workaround of this problem is that you can utilize type object of static class.

Type t = typeof(MyNamespace.UserManager);

 

Using Type object (t) you can gain complete control on object. Now use reflection accessor to read and update private variable

FieldInfo f = t.GetField(("_WorkingDemo",

BindingFlags.NonPublic | BindingFlags.Static);

f.SetValue(t, newValue);


 

Code Example.

// DLL- MyNameSpace.DLL 

namespace MyNamespace

{

    public static class UserManager

    {

 

        private static Boolean _WorkingDemo = false; // this variable not accessable outside class

        public static int GetUsers()

        {

            if (_WorkingDemo)

                return 1;

            else

                return 2;

        }

    }

}

 

// EXE- MyWorkArea.DLL

// Add refrence MyNameSpace.DLL in this project

namespace MyWorkArea

{

    static class Program

    {

        ///

        /// This method is responsible for changeing variable in MyNamespace.UserManager

        ///

        ///

        ///

        private static void changePrivateVar(String privateVariable, Object newValue)

        {

            Type t = typeof(MyNamespace.UserManager);

            FieldInfo f = t.GetField(privateVariable,

            BindingFlags.NonPublic | BindingFlags.Static);

            f.SetValue(t, newValue);

        }

        [MTAThread]

        static void Main(string[] args)

        {

            Console.WriteLine("Pring " + MyNamespace.UserManager.GetUsers());

            changePrivateVar("_WorkingDemo", true);

            Console.WriteLine("Pring " + MyNamespace.UserManager.GetUsers());

            ///OutPut

            ///Print 2 //which is call by regular routine.

            ///Print 1 //Outout change by reflection.

        }

    }

}

 

Reflection is a very powerful feature that any programming language would like to provide, because it allows us to get some information about objects in runtime. It can be used in the applications normally but this is provided for doing some advanced programming. This might be for runtime code generation (It goes through creating, compilation and execution of source code in runtime).