Why is new String(“Hello”) invalid in C#?

后端 未结 9 2501
太阳男子
太阳男子 2021-02-19 03:41

What is the logic/reason behind making

String s= new String(\"Hello World\");

Illegal in C#? The error is

The best over

9条回答
  •  遥遥无期
    2021-02-19 04:32

    At my end, I get this:

    The best overloaded method match for `string.String(char[])' has some invalid arguments

    May be you typed "char *" in place of "char[]" while posting.

    Perhaps this has got to do with our historic understanding of literals. Prior to C#, a value enclosed in quotes (like "astringvalue") could be treated as a character pointer. However in C# "astringvalue" is just an object of type string class. The statement:

    String s= new String("Hello World");
    

    would imply create an object of type String class and invoke its constructor. The compiler checks the list of constructors available for string class. It cannot find any constructor that could accept a string object ("Hello world"). Like in any other situation, the compiler makes a best guess of which is the "closest" method from the list of overloaded methods - in this case, assumes a string value "Hello world" to be closest to a character array (char []) - and tells you that your "Hello world" (value that you passed) is an invalid value for "char []".

提交回复
热议问题