开发者

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

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 argume开发者_C百科nts 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


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.


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";


You are attempting to call a constructor with a string as a parameter.

The compiler is telling you there is no string constructor with a single string as a param.


The type char* is for an unsafe pointer -- to an object not part of the .Net managed framework. When you place the literal string "aaa" in your code, that's a managed object. string is not char* in C#.


have look to this may resolve your doubt C# New String Constructor

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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜