Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.String Type in C#

Tags:

c#

clr

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";
like image 508
Transcendent Avatar asked Dec 12 '13 16:12

Transcendent


2 Answers

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.

like image 85
DGibbs Avatar answered Sep 22 '22 09:09

DGibbs


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.

like image 33
Tim S. Avatar answered Sep 18 '22 09:09

Tim S.