liveBook · Manning

Using-directive

As explained in .NET in Action, Second Edition

A using directive is a C# declaration that makes types in a namespace available without their fully qualified names.

A using directive makes types in a namespace available without repeating their fully qualified names. For example, using System.Text.RegularExpressions lets code write Regex instead of System.Text.RegularExpressions.Regex. section 2.4

Apply using directives with these considerations:

  • Use multiple directives when needed, but fully qualify a type when different namespaces contain types with the same name. section 2.4
  • Place the namespace declaration before or after the using directive; placement has meaning, as the two forms demonstrate. section 2.4
  • Keep types inside namespaces; C# 10 also permits file-level namespace declarations, which reduce indentation. section 2.4
Listing 2.8 namespace after using
using System.Text.RegularExpressions;      #1
  
namespace System.Text;
  
public static class Bar
{
  public static readonly Regex Letters = new Regex(@"[a-z]+");
}

This listing combines a using directive for System.Text.RegularExpressions with a file-level namespace and an unqualified Regex type. section 2.4

How .NET in Action, Second Edition covers it

How deep it goes
Explains namespace lookup, name collisions, and declaration placement through focused C# examples.
Examples
Uses Regex, Figgle, HelloDotnet, and contrasting namespace-placement listings.
What it assumes
Assumes familiarity with C# source structure, namespaces, and type names.
What you can do after
Apply it by importing namespaces and qualifying ambiguous type names when necessary.
How it connects
Connects namespaces, fully qualified names, type-name collisions, and file-level namespace declarations.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of .NET in Action, Second Edition. The section links point to the parts of the book it draws on.