Do you doubt about " insertion" of variables in the input command in C#?

Asked

Viewed 101 times

0

Well, my doubt is this, in C# I can use my "constants" be it of any type in my output command, everything normal.

However, if I use a "variable" of the type int or double and put them in the input command of a Syntax error :

" Convert type ' string ' to ' int ' " or " Convert type ' string ' to ' int ' " .

In error message speaks to me convert, I have to always convert, why when I use string does not appear to convert too?

Anyway , I can talk nonsense but I am very beginner in programming and I would like to clarify this doubt.

inserir a descrição da imagem aqui

  • 2

    Welcome to SO-PT, don’t forget to do the [tour] and understand how the site works. Ideal is that you do not use images but put your code as text, the editor has tools for this, See Help Center How to Ask.

2 answers

1

The method ReadLine() contained within the Console always returns a string(View documentation), therefore, if your variable is not of the type string conversion will be required;

Already the method WriteLine(), also contained in the class Console receives parameters of several different types, see documentation

Take an example:

Console.Write("Digite a nota: ");
if (!int.TryParse(Console.ReadLine(), out int nota))
    Console.WriteLine("Falha ao converter valor para inteiro");
else
    Console.WriteLine($"Nota digitada: {nota}");

With the Console.Write() is being requested an entry, below I try to make a conversion of the entered value to the type int with the int.TryParse, if the entry is converted successfully is written on the screen the typed note, if there is failure, this is informed to the user.

You can also check all this on console class documentation

0

Barbetta’s comment is the best, yet leaving it more simplified.

the code is stating that it does not understand what was typed above, that is because, on the line

Console.Write ("Digite sua nota: ");

is receiving a String (word), however the variable that will receive what was typed is expecting to receive an Int (number).

To fix this just convert the advertised into number as follows:

Convert.ToInt32(Console.ReadLine());

So it will receive what was typed above and then convert what received in number.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.