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";
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With