How to use Console.WriteLine method (C#) – C# Tips

Using the Console.WriteLine function, you can write error logs in console.

Console.WriteLine( "Error" );

or

var error = ...
Console.WriteLine( "Error" + error );

Many types of values (string, int, float, ...) can be variables of Console.WriteLine. So ToString method is not needed.

Sample Program

using System;

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

This code shows "Hello" in the console.

using System;

namespace Hello
{
    class Program
    {
        static void Main( string[] args )
        {
            var word = "World";
            Console.WriteLine( "Hello " + word );
        }
    }
}

This code shows "Hello World" in the console.

Console.WriteLine( string, object[] )

You can also write the code like C's print function:

var title = "English";
Console.WriteLine( "Title : {0}", title );

We can let the second variable be an array with comma delimiters. {0} means the first object of the array.

var title = "English";
var description = "English is ...";
Console.WriteLine( "Title : {0} Description : {1}", title, description );

Sample Program

using System;

namespace Hello
{
    class Program
    {
        static void Main( string[] args )
        {
            var word = "World";
            Console.WriteLine( "Hello {0}", word );
        }
    }
}

This code shows "Hello World" in the console. {0} means "World".

Linefeed (\n)

You can write linefeed (\n) in the console.

using System;

namespace Hello
{
    class Program
    {
        static void Main( string[] args )
        {
            var word = "World";
            Console.WriteLine( "Hello + \n + {0}", word );
        }
    }
}

The code shows like that:

Hello
World

\n meand linefeed.

広告