September 13, 2011

Find memory address of an object in C#

To find memory address of variable is very easy task in C# but when you
want to find address of object it is little bit tedious.We need to use GCHandle
for this.
Example:
class FindAddressOfObject
{
    static void Main()
    {
         Employee objEmp = new Employee ();
         GCHandle ObjGChandle = GCHandle.Alloc(objEmp, GCHandleType.WeakTrackResurrection);
         int ObjAddress = GCHandle.ToIntPtr(ObjGChandle).ToInt32();
         System.Console.WriteLine("The address of object is : {0}", ObjAddress .ToString());
      }
    }
}

That’s It
Enjoy Learning.

No comments:

Post a Comment