deepak baliarsingh
deepak baliarsingh

Reputation: 41

Can not implicitly convert type int to string

When I try to concatenate two characters using the + operator, the compiler displays the following error message: "Can not implicitly convert type int to string."

My code is:

const string Expr = ('$' + (char)(39));

Why do I get this error? And how do I fix it?

Upvotes: 1

Views: 357

Answers (2)

CodesInChaos
CodesInChaos

Reputation: 108800

Using the + operator on two chars doesn't concat them. Instead it converts them to int, and adds these ints, resulting in an int.

A simple solution for your problem is using "$", which is a string, instead of '$', which is a char, but that's no constant expression, so in your case it'll fail with a new compiler error.

Or you could skip the integer step completely and just use const string Expr = "$'". Or if you really want to use an integral codepoint, you can convert it to hex and use "$\u0027".

In some similar situations a common workaround is concatenating with the empty string "" first ("" + a + b). Or you could manually call ToString() on one (or both) of the operands. But in your case turning the $-prefix into string is cleaner.

Upvotes: 9

Botz3000
Botz3000

Reputation: 39610

Just use String.Concat:

string.Concat('$', (char)39)

The + operator on strings is internally translated to that method anyway.

Also, you can't use the const keyword with an expression like that. consider using readonly instead.

Upvotes: 1

Related Questions