How to fix this error "Cannot convert from 'int'to' char []'
2 answers
Formatting output
The first argument of the WriteLine
method must be a string.
This string can contain markers to insert into it, the following arguments:
Console.WriteLine("{0} {1} {2}", centena, dezena, unidade);
About error
The error indicated occurs because the method WriteLine
has more than one way to be called. One of these forms gets char[]
in the first argument, followed by two int
s. what happens is that the compiler is evaluating the possible alternatives, and it found that that's what you wanted to call it.
See the documentation for this method .
There are several overloads to call it, each handles the information in a different way. Most are for basic types of language and as can be seen only accept one argument.
A overload that accepts multiple arguments cannot be used directly, the first argument must be a string with the formatting that will be applied to the content and then the arguments that must be printed using this formatting. This is the one you should use.
There is one that accepts more than one argument. Since this overload accepts int
as the second and third argument, it's the one that came closest to what it looks like it needs, so the compiler mistakenly chooses this one.
This is called betterness.
In this case the ideal is to use interpolation of string, avoids a lot of problem and becomes more readable (there are those who disagree). Like this:
using static System.Console;
public class Program {
public static void Main() {
WriteLine("Digite um número com três dígitos");
if (int.TryParse(ReadLine(), out var numero) && numero < 10000) WriteLine($"{numero / 100} {(numero % 100) / 10} {(numero % 100) % 10}");
}
}
See not working ideone. And no .NET Fiddle. Also I put on GitHub for future reference .
Fixed other code issues and made it more efficient and simple.