# Console Output

There are two methods that you can use to write to the console.

  1. Console.Write()
  2. Console.WriteLine()

Notice the L is capital in WriteLine,

Both these methods are present in the Console class, which itself in present in System namespace.

There are two ways to use these methods.

# Method 1 – using directive

 





 



using System;

class MainClass
{
  public static void Main ()
  {
      Console.Write("Hello");
  }
}
1
2
3
4
5
6
7
8
9

Line 1 tells the compiler that the following code is using System namespace. using is a directive for the compiler.

# Method 2 – fully qualified type name





 



class MainClass
{
  public static void Main ()
  {
      System.Console.Write("Hello");
  }
}
1
2
3
4
5
6
7

Line 5 uses a fully qualified name to tell the compiler, use function Write from Console class which is present in System namespace.

# using directive vs fully qualified type name

Compiler uses using directive and converts code to fully qualified names. As a result, there is no difference in the performance.

# 👍 Best Practice

If your code uses classes from System namespace several times, then it is best to use the using System; directive.

using System;

class MainClass
{
  public static void Main ()
  {
      Console.Write("Hello");
      Console.Write(" ");
      Console.Write("World");
      Console.Write("!");
      Console.Write("\n");
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13

# 👎 Bad Practice

WARNING

The following style of code is bad. Do not use it.

Using fully qualified name several times makes your code repetitive and hard to read.

class MainClass
{
  public static void Main ()
  {
      System.Console.Write("Hello");
      System.Console.Write(" ");
      System.Console.Write("World");
      System.Console.Write("!");
      System.Console.Write("\n");
  }
}
1
2
3
4
5
6
7
8
9
10
11

You can use fully qualified name if you use a class once or twice in your code. Or if there is a name collision.

What is a name collision?

Let's suppose you have create a namespace MyNameSpace. You create a class in it Console.

using System;
using MyNameSpace;

class MainClass
{
  public static void Main ()
  {
      Console.Write("Hello");
  }
}
1
2
3
4
5
6
7
8
9
10

In this code, how will compiler know which Console class you want to use? Compiler will get confuse. Does the developer want to use Console class present in the System namespace or the one present in the MyNameSpace.

This confusion is called name collision.

Last Updated: Apr 26, 2020, 7:00 PM