Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

c# - Why don't we use new operator while initializing a string?

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 while initializing the string ? I said because the c# language has a simpler syntax for creating a string and the compiler automatically converts the code into a call for the construcor of the System.String class.

Is this answer correct or not ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Strings are immutable reference types. There's the ldstr IL instruction which allows pushing a new object reference to a string literal. So when you write:

string a = "abc";

The compiler tests if the "abc" literal has already been defined in the metadata and if not declare it. Then it translates this code into the following IL instruction:

ldstr "abc"

Which basically makes the a local variable point to the string literal defined in the metadata.

So I would say that your answer is not quite right as the compiler doesn't translate this into a call to a constructor.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...