Last Updated:

Assigning a Keyboard Value in C# (sharp)

There is a need to get some data from the user (registration data, variable value and much more), for this we will use the input function called . ReadLine().

To assign a variable, you will have to be a little cunning.
The trick is that any keyboard input is character input. That is, when we type a number from the keyboard, we enter a non-numeric value into a character value. It turns out that we enter the number 100, and the compiler understands this as a string consisting of three characters "100". It will not be possible to work with such a received value as with a number. The entered value must be converted to a number using conversion.

Assign an integer entered from the keyboard to a certain variable, and also slightly format the output for a more understandable interaction with the program.

Run this code and enter any integer. The variable num contains an integer. Conversion works in this case as follows:

  1. First, enter a value that belongs to a character type;
  2. Then, after pressing enter, the value is converted to type int;
  3. Finally, the received and converted value is assigned to the variable num;

Regarding the conversion to the int type, the environment will offer you several options (. ToInt16, . ToInt32, . ToInt64), these numbers at the end indicate the bit depth of the system. The higher the bit, the greater the range of values for the type. Use in the early stages of your knowledge. ToInt32 and you can't go wrong.