cannot implicitly convert type int to string

Пишет — Cannot implicitly convert type ‘double’ to ‘string’

private void button1_Click(object sender, EventArgs e)
<

double x = 0.5;
double r = 3.9999;

for (double i = 0.1; i Голосование за лучший ответ

I am new to C# and the above code show error.. can anyone help?

4 Answers 4

txtbankid.Text property type is a string. Don’t use int.parse . There is no need to. Just do: txtbank >

int.Parse(..) is for converting a string containing digits into an integer. You are trying to perform the function int.Parse(..) on a string but then assign it to another string. That won’t work because int.Parse(..) returns and integer. Read here about Int32.Parse (String) method.

If you want to ensure that the value is an integer before assigning it I suggest you use TryParse

Not the answer you’re looking for? Browse other questions tagged c# or ask your own question.

Hot Network Questions

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2019 Stack Exchange Inc; user contributions licensed under cc by-sa 4.0 with attribution required. rev 2019.11.15.35459

C# allows implicit conversions of integers to strings when used in an expression. For example, this is completely valid:

However, when the int is not being concatenated or interpolated, C# requires an explicit conversion.

Obviously this isn’t a major pain: a simple .ToString() takes care of this just fine. But if .NET knows that every possible int is also a valid string, why does it still require an explicit conversion? I’d like to know what’s going on in the «mind» of the compiler.

3 Answers 3

In both cases, the language is offering syntactic sugar features, rather than doing implicit casting:

is converted to the string Concat(object, object) method during compilation:

And in the second case,

is converted to string Format(string, object) (or equivalent) method during compilation:

So in both cases, the int is being boxed to an object and each method then calls .ToString() on that object. No implicit casting is required.

As for the question in your title: «Why can’t C# implicitly convert int to string?», the answer to that, is that neither the String class, not the Int32 struct implement the implicit operator , so implicit conversions aren’t possible between those types. You might be interested to know though that post C# 7, one feature being considered for the language is called «Extension everything». This would allow you to add implicit conversions between various types and strings to the language, such that you could do something like:

if you really wanted to. Of course, that raises the question, would you want to?

Оцените статью