Intro
This post is an addition to one of the lectures from our C# Masterclass. It also contains the course code and extra code samples.
The Console class in C# is a handy tool for developers. It provides a convenient way to interact with the command line, allowing you to input and output data, and display messages to the user. Whether you’re writing a simple command line application or a more complex system, the Console class offers a range of methods that make it easy to get started. In this article, we’ll take a look at the most commonly used methods of the Console class and provide examples of how you can use them in your own code.
The most popular methods of the Console class
The first method we will look at is WriteLine. This method is used to write a line of text to the console. You can pass in a string or an object, and the text representation of that object will be displayed on the console. For example:
Console.WriteLine("Hello, world!");
The next method is ReadLine, which reads a line of text from the console. When this method is called, the program will wait for the user to input a line of text, and then return it as a string. For example:
string name = Console.ReadLine(); Console.WriteLine("Hello, " + name + "!");
In this example, the program will wait for the user to enter their name and then greet them with a personalized message.
The Write method is also frequently used. This method is used to write a single character or a string to the console. For example:
Console.Write("Enter your name: "); string name = Console.ReadLine(); Console.WriteLine("Hello, " + name + "!");
Finally, the Read method reads a single character from the console. For example:
Console.Write("Enter a character: "); char c = Console.Read(); Console.WriteLine("\nYou entered: " + c);
In this example, the program will ask the user to enter a character and then read that character using the Read method.
In conclusion, the Console class in C# is a valuable resource for developers. By using the Read, ReadLine, Write, and WriteLine methods, you can easily interact with the command line and accomplish a wide range of tasks. Whether you are writing a simple or a more complex system, the Console class is a versatile tool that will help you get the job done.
Source code for the lecture
Console.WriteLine("Enter a string and press enter :"); string readInput = Console.ReadLine(); Console.WriteLine("You entered {0}",readInput); Console.Write("Enter a char and press enter: "); int asciiValue = Console.Read(); Console.WriteLine("ASCII value is {0}", asciiValue);
If you want to skyrocket your C# career, check out our powerful ASP.NET FULL-STACK WEB DEVELOPMENT COURSE, which also covers test-driven development and C# software architecture.