How to get user input and use it
This article is about how to get user input in CSharp. This is basically an important functionality of a program. Sure, there are programs that work by themselves without any user input. In most cases, however, it is needed. There are different ways to interact with the program. E.g. text input, buttons, swipes, touches and many more. However, we will look at the text input in this article. We’ll keep it pretty simple for now. Since we have not yet worked with loops and if statements.
Example for User Input in CSharp
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Panjutorials { class Program { static void Main(string[] args) { string input = Console.ReadLine(); Console.WriteLine(input); Console.Read(); } } }
So we now have a program that converts the text we enter into a string and saves it within the variable input. This is then used to output it to the console. We can now extend the program to write a small adder.
Example of an adder in CSharp
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Panjutorials { class Program { static void Main(string[] args) { int num1 = 0; int num2 = 0; int summe = 0; // empty input variables n string input1= ""; string input2 = ""; // We show to the user what he needs to do Console.WriteLine("Please enter the first number"); input1= Console.ReadLine(); Console.WriteLine("Please enter the second number"); input2= Console.ReadLine(); // Convert input of the user into an intiger with 32 bit // this is rather error prone as the user could enter // something which is not a number, this would crash our application num1 = Convert.ToInt32(input1); num2 = Convert.ToInt32(input2); // add the two numbers sum = num1 + num2; // Output of the values with concattination Console.WriteLine("The solution is " + sum); Console.Read(); } } }
So our new program can now easily add two values together. As described in the code as comments, this is very error-prone. We have not yet dealt with the possibility of intercepting these errors, but will still do so later on in the course.