Lession - 2 Methods and Properties of Console Class in C#
Lession - 2 Methods and Properties of Console Class in C#
Now, we are going to discuss the Methods and Properties of Console class in C# with Examples.
Here, we are going to discuss the following pointers.
1. What is Console Class in C#?
2. Properties of Console Class in C#.
3. Methods of Console class in C#.
4. Understanding the use of the Write and WriteLine method in C#.
5. Program to show how to print the value of a variable in a console application.
6. Understanding the use of the ReadLine method in C#.
7. Program to show the use of BackgroundColor, ForegroundColor, and Title properties
of Console class.
In order words, if we want to work with the console window either for taking user input or to show the
output, we are provided with the Console in C#.
According to Microsoft documentation the Console class represents the standard input, output, and
error streams for console applications and this class cannot be inherited because it is a static class
i.e. declared as static as shown in the below image.
The static class in C# contains only static members i.e. all the Properties and Methods available in the
Console class are static. So, we can access all these members by using the Console class name i.e.
we don’t require the Console class instance to access these members.
Example to show the use of the Write and WriteLine method in C#:
The following example code is self-explained, so please go through the comment lines.
//WriteLine Method Print the value and move the cursor to the next line
Console.WriteLine("Hello");
//Write Method Print the value and stay in the same line
Console.Write("HI ");
//Write Method Print the value and stay in the same line
Console.Write("Bye ");
//WriteLine Method Print the value and move the cursor to the next line
Console.WriteLine("Welcome");
//Write Method Print the value and stay in the same line
Console.Write("C#.NET ");
Console.ReadKey();
}
}
}
Output:
Note: The ReadLine method always accepts the value in the form of a string. So, we need to convert
the values to the appropriate type. In the above example, we are converting the values to integer type
by using Convert.ToInt method. We will discuss this method in detail in out upcoming sessions.
Console.ReadKey();
}
}
}
Output:
Complex Example to Understand Console Class:
Now, we will write one program to accept Employee Details like EmployeeId, Name, Salary, Address,
Department, and then we will print the accepted information on the console window.
//Program to show the use of Console Class
using System;
namespace MyFirstProject
{
internal class Program
{
static void Main(string[] args)
{
//Ask User to Enter the Employee Details
Console.WriteLine("Enter Employee Details");