C # display the memory address of the referenced type variable (take string as an example)
For C/OC/C ++ programmers, it is common to output the memory address of the created object and observe, analyze, or simply be curious.
However, for the C # language that puts security first, this "normal thing" seems not so straightforward.
Based on stackoverflow's Q & A, this article encapsulates the method for displaying the address of the reference type memory in C # language,
Take the System. String and StringBuilder classes as examples to show their memory address changes.
First, select "allow Insecure code" in the Project Settings"
Second, write the source code as follows:
////// Get the memory address of reference type. // obtain the memory address of the reference type // Created by duzixi.com 2014.11.27 // www.lanou3g.com All Rights Reserved ///Using System; using System. text; using System. runtime. interopServices; namespace GetMemory {class MainClass {public static string getMemory (object o) // method for obtaining the memory address of the reference type {GCHandle h = GCHandle. alloc (o, GCHandleType. pinned); IntPtr addr = h. addrOfPinnedObject (); return 0x + addr. toString (X);} public static void Main (string [] args) {// immutable string System. stringstring str1 = immutable string; string str2 = str1; string str3 = str1; str2 = new string; // when a new value is assigned, open up new space, Console. writeLine (str3); // It does not change // str2 points to the new address, and the rest remains unchanged on the Console. writeLine (str1: + getMemory (str1); Console. writeLine (str2: + getMemory (str2); Console. writeLine (str3: + getMemory (str3) +); // variable string StringBuilderStringBuilder txt = new StringBuilder (variable string); StringBuilder aTxt = txt; StringBuilder bTxt = txt; aTxt. append (Append another string); Console. writeLine (bTxt); // The content of another referenced string changes accordingly. // The memory address remains unchanged. Console. writeLine (txt: + getMemory (txt); Console. writeLine (aTxt: + getMemory (aTxt); Console. writeLine (bTxt: + getMemory (bTxt ));}}}
The magic GCHandle and related methods still need to be studied. However, from the running results, this can already explain some memory problems.