Write to Console in C#

Console.WriteLine method is used to write strings, objects, integer or any other types to the Console in String format.

Examples

ADVERTISEMENT

1. Write string to console

Following is an example, where we write a string to console output.

C# Program

using System;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
    }
}

Output

PS D:\workspace\csharp\HelloWorld> dotnet run
Hello World!

WriteLine method writes the provided string and ends with a line terminator, which is by default a new line.

2. Write values of different data types to console

C# Program

using System;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            Console.WriteLine(125);
            Console.WriteLine(true);
            Console.WriteLine(52.14);
            Console.WriteLine(-963);
            string msg = "C# tutorial by TutorialKart";
            Console.WriteLine(msg);
            Console.WriteLine();
            Console.WriteLine('m');
        }
    }
}

Output

PS D:\workspace\csharp\HelloWorld> dotnet run
Hello World!
125
True
52.14
-963
C# tutorial by TutorialKart

m

All the data passed as arguments are first converted to text representations and then printed on to the console.

When you provide no argument to Console.WriteLine(), then it would just print the line terminator (new line). Hence, in the above example, for the last but one WriteLine(), the corresponding output is an empty line followed by new line character.

Also, we can pass an object or a variable to the console.

string msg = "C# tutorial by TutorialKart";
Console.WriteLine(msg);

In this part of the code, we have passed a variable to the WriteLine.

Conclusion

In this C# Tutorial, we have learned to write string or values belonging to different datatypes to the console.