System.String Type in C #

I know this may seem like a strange question, but it went on in my head for a while.

I know that the System.String type in C # is actually a class with a constructor that has a character array parameter. For example, the following code is legal and does not cause an error:

System.String s = new System.String("Hello".toCharArray()); 

My question is what makes it possible for the System.String class to accept an array of characters just like this:

 System.String s = "Hello"; 
+6
source share
3 answers

When you call:

 System.String s = new System.String("Hello".toCharArray()); 

You explicitly call the constructor

When you write:

 string foo = "bar"; 

The IL ( Ldstr ) statement pushes a new object reference for this string literal. This is not the same as calling a constructor.

+8
source

This is possible because the C # language indicates that string literals are possible (see 2.4.4.5 String literals). The C # compiler and CIL / CLR have good support for how these literals are used, for example. using the ldstr code.

There is no support for including such literals for native custom types.

+3
source

Strings are a special type of clr. They are the only immutable reference type.

Here are a few things that can help you understand the type of string:

  var a = "Hello"; var b = new String("Hello".ToCharArray()); var c = String.Intern(b); // 'interns' the string... var equalsString = a == b; // true var equalsObj = (object)a == (object)b; // false var equalsInterned = (object)a == (object)c; // true !! a[0] = 't'; // not valid, because a string is immutable. Instead, do it this way: var array = b.ToArray(); array[0] = 't'; a = new String(array); // a is now "tello" 
-2
source

All Articles