[Solved] How do you have user integer input in C#? [closed]


bThere are several problems in your code.

On the fourth line you have

int Test = Console.ReadLine();

Console.ReadLine() does not return an int, but a string.

string Test = Console.ReadLine();

The name Test is not very descriptive and also violates the convention, that local variables should start with lower-case letter. So we can further improve the line to:

string input = Console.ReadLine();

Since C# 3 we also have implicit typing in form of var – thanks to this the compiler is able to automatically replace var with the type of the value on the right-hand side of the expression. In this case a string. So you could write the line as the following.

var input = Console.ReadLine();

As @PMV mentioned however, leaving string there instead of var results in better readability, because the return type on the right hand side is not clear from the name of the method.

The next line again violates variable naming conventions, int value or int number would be preferable. Integer could also be mistaken as type name for many developers coming from different languages – like Java. Note that we cannot use var here, because there is not right-hand side (nothing is assigned to the variable) and hence compiler has no way to recognize the type.

By now the error message should be gone, because we have changed the name of the Test variable. The error you have received tells you that you have redeclared the variable with the same name in the inside scope (inside the first if statement branch). This is not allowed in C#, because the outside scope variables are visible from the inner blocks.

Inside the first if block you also are trying to convert to int but this is an invalid statement, as you give the method no input and also you already have the parsed number after using TryParse

using System;

class MainClass {
    public static void Main (string[] args) {
        string input = Console.ReadLine();
        int value;
        if ( int.TryParse( input, out value ) )
        {
            //the user input is now stored in the 'value' variable
            //and you can normally use it as a number
            Console.WriteLine( value + 4 );
        }
        else
        {
            Console.WriteLine("::INVALID::")
        }
    }
}

8

solved How do you have user integer input in C#? [closed]