Every program needs a way to interact with the user. You need to display information and accept input. In C#, this is actually very straightforward.
Displaying Output
You have already seen Console.WriteLine() in action. But there is also
Console.Write(). What is the difference?
Console.Write("Hello ");
Console.Write("World");
Console.WriteLine("!");
// Output: Hello World!
Write() prints the text and stays on the same line. WriteLine() prints
the text and moves to the next line. Most of the time, you will use WriteLine(),
but Write() is useful when you want to build output piece by piece.
String Interpolation
Remember how we concatenated strings with the + operator? There is a cleaner
way โ string interpolation. Just put a $ before the opening quote and wrap
variables in curly braces:
string name = "Chukwuemeka";
int age = 24;
// The old way
Console.WriteLine("Name: " + name + ", Age: " + age);
// String interpolation โ much cleaner
Console.WriteLine($"Name: {name}, Age: {age}");
String interpolation is easier to read and less error-prone. Once you start using it, you will never want to go back to concatenation.
You can also do math inside the curly braces:
int price = 500;
int quantity = 3;
Console.WriteLine($"Total: {price * quantity}"); // Total: 1500
Reading Input
To get input from the user, use Console.ReadLine(). It waits for the user to
type something and press Enter, then returns whatever they typed as a string:
Console.Write("Enter your name: ");
string name = Console.ReadLine();
Console.Write("Enter your age: ");
string ageInput = Console.ReadLine();
Console.WriteLine($"Hello {name}, you are {ageInput} years old.");
Notice that ReadLine() always returns a string. Even if the user types a number,
it comes back as a string. This is important to remember because you will often need to
convert it to a number before doing math with it. We will cover type conversion in the
next lesson.
Reading Different Types
If you need to read a number directly, you can use methods like int.Parse()
or Convert.ToInt32():
Console.Write("Enter your age: ");
int age = int.Parse(Console.ReadLine());
Console.Write("Enter your height: ");
double height = Convert.ToDouble(Console.ReadLine());
Console.WriteLine($"In 10 years, you will be {age + 10} years old.");
Be careful though โ if the user types something that is not a number, your program will crash. We will learn how to handle that with exception handling later on.