Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are strings VS chars handled in C# vs Javascript?

Tags:

string

c#

In JavaScript, single and double quotes are somewhat interchangeable and largely a matter of styles (There is a good discussion of why this isn't actually the case in one of the answers here: When to use double or single quotes in JavaScript?). How are chars and strings handled in C#?

For example:

string test = "hello world";
string test2 = 'hello world'; // Too many characters in character literal
char test3 = 'a';
char test4 = "a"; // Cannot implicitly convert type string to char

It looks like strings and chars are being handled as separate, interchangeable types, and that the use of single or double quotes demarcates this?

What is the relationship between chars and strings in typed languages? Specifically, would it be correct to say that a string is an array of chars?

like image 885
Zach Smith Avatar asked Sep 11 '26 23:09

Zach Smith


1 Answers

would it be correct to say that a string is an array of chars

In .NET, a string is an object containing a contiguous block of memory containing UTF-16 code units. A char is another (primitive) data type that just contains one code point, with no object overhead.

From this interesting blog post from Jon Skeet, where he compares the .NET vs. Java implementation:

A long string consists of a single large object in memory. Compare this with Java, where a String is a “normal” type in terms of memory consumption, containing an offset and length into a char array – so a long string consists of a small object referring to a large char array.

like image 73
Patrick Hofman Avatar answered Sep 14 '26 12:09

Patrick Hofman