Search code examples
c#.netstringbstrnull-terminated

Why are C#/.NET strings length-prefixed and null terminated?


After reading What's the rationale for null terminated strings? and some similar questions I have found that in C#/.NET strings are, internally, both length-prefixed and null terminated like in BSTR Data Type.

What is the reason strings are both length-prefixed and null terminated instead of eg. only length-prefixed?


Solution

  • Length prefixed so that computing length is O(1).

    Null terminated to make marshaling to unmanaged blazing fast (unmanaged likely expects null-terminated strings).