I was asked this question in an interview: Is string a reference type or a value type.
I said its a reference type. Then he asked me why don\'t we use new operator
Well, it's correct that the compiler has special syntax that simplifies the creation of strings.
The part about the compiler producing a call to the constructor is not really correct. String literals are created when the application starts, so where the string literal is used it's only an assignment of a reference to an already existing object.
If you assign a string literal in a loop:
string[] items = new string[10];
for (int i = 0; i < 10; i++) {
items[i] = "test";
}
it will not create a new string object for each iteration, it will just copy the same reference into each item.
Two other noteworthy things about string literals is that the compiler doesn't create duplicates, and it automatically combines them if you concatenate them. If you use the same literal string more than once, it will use the same object:
string a = "test";
string b = "test";
string c = "te" + "st";
The variables a, b and c all point to the same object.
The string class also has constructors that you can use:
string[] items = new string[10];
for (int i = 0; i < 10; i++) {
items[i] = new String('*', 42);
}
In this case you will actually get ten separate string objects.