Friday, March 5, 2010

Invoke private static method and assign static variable through reflection c#

I was working on current project and wanted to update some of the values of the fields which were private to the method and were being updated from one of the private methods.
The assembly which was being reference was not allowing any of the methods or fields, using which I could have updated the values runtime, so I end up using reflection.
Here is the code snippet for the same:

//Get the type of the class

Type typeToChangeValue = Assembly.GetAssembly("YourAssemblyName").GetType("TypeName");

//Get the static field to set the value

FieldInfo
fieldToSetValue =
typeToChangeValue.GetField("FieldName", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.GetField);
//Get the method of which output you want to assign to a variable
MethodInfo privateStaticMethod = typeToChangeValue.GetMethod("StaticMethodName", BindingFlags.NonPublic | BindingFlags.Static);
//Invoke the method

object
returnValue = privateStaticMethod.Invoke(typeToChangeValue, new object[] { "methodParams" });

//define class variable

TypeName classObject = new TypeName();

//Invoke reflection setvalue method to assign the returned value of the method

fieldToSetValue.SetValue(classObject, returnValue);