Troskyvs
Troskyvs

Reputation: 8047

C#: why string cannot be constructed with a string literal as parameter?

static void Main(string[] args) 
{ 
    string s = new string("abc"); 
    string s2 = "abc"; 
}

Well this program has compiling error in first line, the string constructor cannot accept a string literal, while the 2nd line compiles OK.

So what's the difference between line 1 and line 2, I suppose they're both constructors, why 1st line has compilation error?

Upvotes: 0

Views: 55

Answers (1)

Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

Reputation: 34152

C# string constructor only accept these arguments which string is not one of them:

unsafe public String(char*);
       public String(char[]);
unsafe public String(sbyte*);
       public String(char, int);
unsafe public String(char*, int, int);
       public String(char[], int, int);
unsafe public String(sbyte*, int, int);
unsafe public String(sbyte*, int, int, Encoding); 

http://www.dotnetperls.com/string-constructor

Upvotes: 1

Related Questions