Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 630
prostynick Avatar asked Jun 09 '11 13:06

prostynick


People also ask

Why are we using C?

C is a general-purpose programming language and can efficiently work on enterprise applications, games, graphics, and applications requiring calculations, etc. C language has a rich library which provides a number of built-in functions. It also offers dynamic memory allocation.

Why is C not A or B?

Because C comes after B The reason why the language was named “C” by its creator was that it came after B language. Back then, Bell Labs already had a programming language called “B” at their disposal.

Why is C so popular language?

The C programming language is so popular because it is known as the mother of all programming languages. This language is widely flexible to use memory management. C is the best option for system level programming language.

Why is it called C++ and not ++ C?

C++ was originally called 'C with classes,' and was built as an extension of the C language. Its name reflects its origins; C++ literally means 'increment C by 1. ' It was renamed C++ in 1983, but retains a strong link to C, and will compile most C programs.


2 Answers

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

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

like image 111
jason Avatar answered Sep 28 '22 11:09

jason


Here is an excerpt from Jon Skeet's Blog Post about strings:

Although strings aren't null-terminated as far as the API is concerned, the character array is null-terminated, as this means it can be passed directly to unmanaged functions without any copying being involved, assuming the inter-op specifies that the string should be marshalled as Unicode.

like image 21
Xaisoft Avatar answered Sep 28 '22 11:09

Xaisoft