Where does .NET place the String value?

随声附和 提交于 2019-11-28 23:27:44

At m_firstChar. The heap allocation is large enough to fit the entire string, not just the first character. Easy to see in Visual Studio as well:

class Program {
    static void Main(string[] args) {
        string s = "hello" + "world";
    }  // <=== Breakpoint here
}

When the breakpoint hits, use Debug + Windows + Memory + Memory1. In the Address box type s. You'll see:

0x01B3F6BC  e8 0a 67 6e 0b 00 00 00 0a 00 00 00 68 00 65 00  è.gn........h.e.
0x01B3F6CC  6c 00 6c 00 6f 00 77 00 6f 00 72 00 6c 00 64 00  l.l.o.w.o.r.l.d.
  • The object starts at the address - 4, the syncblk is stored there (not visible).
  • Next 4 bytes is the method table pointer (0x6e670ae8, aka type handle).
  • Next 4 bytes is the m_arrayLength member, the allocated size of the string (0x0b).
  • Next 4 bytes is the m_stringLength member, the actual number of characters in the string (0x0a).
  • Next bytes store the string, starting at m_firstChar.

This is for .NET 3.5 SP1. You won't see the m_arrayLength member in .NET 4.0 and up, the field was removed.

Like a C "string", it's stored in the m_stringLength bytes starting at m_firstChar which is an unsafe pointer, not an actual character. C# uses a length prefixed string rather than a null delimited one though.

That said, the beauty of the CLR is that you don't need to care. How has this become an issue?

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!