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
