Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why string str = new string("abc") doesn't pass compiler?

Tags:

string

c#

Given public String(char*) why we cannot use the following statement?

string str = new string("aaa");

Error 1

The best overloaded method match for 'string.String(char*)' has some invalid arguments C:\temp\ConsoleApplication2\ConsoleApplication2\Program.cs 19 26 ConsoleApplication2

Error 2

Argument 1: cannot convert from 'string' to 'char*' C:\temp\ConsoleApplication2\ConsoleApplication2\Program.cs 19 37 ConsoleApplication2

like image 784
q0987 Avatar asked Jul 03 '26 13:07

q0987


2 Answers

Simply use:

 string str = "aaa";

You do not need to new a string.

"aaa" is a string. It is not a char *.
char * is used with unsafe code.

like image 60
Richard Schneider Avatar answered Jul 05 '26 04:07

Richard Schneider


Because this isn't meant to be used in safe code...

In C#, this constructor is defined only in the context of unsafe code.

from: http://msdn.microsoft.com/en-us/library/6y4za026.aspx

If you need to construct a string you could just use the literal decleration..

string str = "aaa";
like image 21
Quintin Robinson Avatar answered Jul 05 '26 03:07

Quintin Robinson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!