What are the advantages of using 'using' keyword in C# and why would you use it?

Experience Level: Junior
Tags: C#

Answer

  • The keyword using is used at the top of the .cs file to tell the computer in which namespaces to look for the classes that are referred to from the file.
  • In the first example below, the class OakTable will be searched for in the namespaces System and Furniture.Tables.
  • In the second example below, the class OakTable is defined by the fully qualified name that includes the namespace. You can see that the code for creation new instance of class OakTable in the first example is way shorter than the one in the second example. This is the advantage of using the keyword  using. It helps to reduce the code duplication.
Example 1
using System;
using Furniture.Tables;

namespace House {
  class Program {
    public static void Main() {
      var myTable = new OakTable();
    }
  }
}
Example 2
namespace House {
  class Program {
    public static void Main() {
      var myTable = new Furniture.Tables.OakTable();
    }
  }
}
Related C# job interview questions
C# for beginners
C# for beginners

Are you learning C#? Try our test we designed to help you progress faster.

Test yourself