Share via


What's yours... is mine...

   Here is something that I played with today that I think it's very interesting so I' thought I'd share.

   I have created a class called ClassLibrary1 (I know.. how original!)... looks like this:

using System;

using System.Collections.Generic;

using System.Text;

namespace ClassLibrary1

{

    public class Class1

    {

        private string myString = "Old Value!";

        public string Test()

        {

            return myString;

        }

    }

}

   Now, I want to change the private string myString but still use the Test function. Can this be done? Alas! Yes.. it can.. with reflection..

  To load the ClassLibrary1 assembly in my ASP NET application, all I have to do is drop a copy of it in the bin directory of my application. In case you don't know, that's all you have to do.. you don't have to call Assembly.Load, ASP NET will automagically load all assemblies it finds in the bin directory for us. I'll prove it in a sec..

   Now if I call the Test function from my application, it will return the string "Old Value!". But I don't want that.. I want the string to be "New Value!" from now on. Here's how I can use reflection to change the private field in ClassLibrary1.dll:

Class1 myClass = new Class1();

Type myType = myClass.GetType();

       

FieldInfo myFieldInfo = myType.GetField("myString",BindingFlags.NonPublic | BindingFlags.Instance);

myFieldInfo.SetValue(myClass, "New Value!");

   Here's the breakdown of the above code:  

  •    I must first instantiate an instance of my class.
  •    I then need the type of my class so I can get to the GetField method.
  •    I then use the FieldInfo Class to change the private string.
  •    I can then call the SetValue function of the FieldInfo class which needs to know which instance of my class to change.

    VoilĂ !

   Now when I call my Test function, it will return the new value I wrote:

Response.Write(myClass.Test());

   This returns : "New Value!".

   Pretty powerful stuff, if you think about all the potential uses...

   Enjoy!

Comments

  • Anonymous
    July 10, 2007
    The comment has been removed
  • Anonymous
    July 11, 2007
    The comment has been removed