When compiling, it does not give an error, but it gives out not what was expected, that is, when I write the number 7 the compiler infers that it is a string, do not tell me what is the error?

using System; public class Test { public static void M(int i) { Console.WriteLine("это обычное число"); } public static void M(string i) { Console.WriteLine("это строка"); } public static void Main() { var b=Console.ReadLine(); M(b); } } 
  • one
    ReadLine always returns only a string, everything is correct - andmal
  • you misunderstand, the code I have prescribed that if it is an integer variable, it outputs "this number", if this is a string, then it should output "this is a string" - Midas
  • If you want to determine if the value in the line looks like a number, see stackoverflow.com/questions/894263/… - andreymal
  • 2
    You yourself would understand what this was about, what's the problem? Replace - vikttur
  • All characters read from the terminal are of type String by default. Those. In your case, the variable 'b' is always String, and you need to do checks for a numeric value and call the desired method. - ahgpoug

1 answer 1

See it.

When Console.ReadLine reads the input text, it reads only the characters entered, and places them on the line. Console.ReadLine does not check if your characters can be interpreted as a number or something else.

Variable b is of type string , always. In fact, var does not mean "guess the real type of the variable", it means "take the type that is on the right side of the expression." And since the type of the right side of the expression is string , the type b also string .

Therefore, overloading with int will never be called.


In order to find out if there is a number in the entered string, you need to use the int.TryParse method:

 if (int.TryParse(b, out int n)) M(n); else M(b); 

Here the type is n - int , so the necessary overload will be called.