Frage

I know that it may sound like a weird question but this has been going on in my mind 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 causes no error:

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

My question is that what makes is possible for the System.String class to accept an array of characters simply this way:

System.String s = "Hello";
War es hilfreich?

Lösung

When you call:

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

You are explicitly invoking a constructor

When you write:

string foo = "bar";

An IL instruction (Ldstr) pushes a new object reference to that string literal. It's not the same as calling a constructor.

Andere Tipps

This is possible because the C# language specifies 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, e.g. with the ldstr opcode.

There is no support for including such literals for your own custom types.

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

Here are several things which may help you to understand string type:

 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"
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top