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

后端 未结 9 2447
太阳男子
太阳男子 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:33

    In my opinion, The basic difference is the 'Pass by Reference' and 'Pass by Value' in .NET and JAVA.

    Leading to a design pattern in Java, for a reason which may be

    A constructor for copying an object of the same class.

    In .NET you don't require such constructor to copy/clone the string because it can do it in following way (directly),

    'String test = txtName.Text;'

    This is my understanding of .net and java.

    I hope I was able to give proper reasoning.

    Thanks and Regards

    Harsh Baid

    0 讨论(0)
  • 2021-02-19 04:44

    It's .NET, not C#. Look at the constructors for System.String - none accept a System.String

    So it's "illegal" for the same reason you can't construct a string with an int.

    string x = new String(1);
    

    Raymond Chen

    The answer to "Why doesn't this feature exist?" is usually "By default features don't exist. Somebody has to implement them."


    My guess is that every time someone sat down to implement this constructor. They thought about String.ToString's implementation and determined the constructor would logically undermine that method.

    0 讨论(0)
  • 2021-02-19 04:45

    It would be rather pointless to use the constructor to create a new string based on another existing string - that's why there is no constructor overload that allows this. Just do

    string s = "Hello World";
    
    0 讨论(0)
提交回复
热议问题