DEV Community

Cover image for C# - Global Using Directives for Cleaner Code
Keyur Ramoliya
Keyur Ramoliya

Posted on

C# - Global Using Directives for Cleaner Code

In C#, Global using directives, a feature that allows you to specify using directives that are applied globally across your entire project. This can significantly reduce the amount of boilerplate code in your files, especially for commonly used namespaces.

Here's how to effectively use global using directives:

  1. Declare Global Usings:
    You can declare a global using directive in any C# file with the global modifier before the using keyword. It's a good practice to place these declarations in a separate file (like GlobalUsings.cs) for better organization.

  2. Project-Wide Application:
    Once declared, the global using directives apply to all the source files in your project. This means you don't need to repeat common using directives in every file.

Example:

In a GlobalUsings.cs file:

global using System;
global using System.Collections.Generic;
Enter fullscreen mode Exit fullscreen mode

In other C# files:

// No need to include 'using System;' or 'using System.Collections.Generic;'

public class MyClass
{
    public void MyMethod()
    {
        List<int> myList = new List<int>();
        Console.WriteLine("Hello, World!");
    }
}
Enter fullscreen mode Exit fullscreen mode

By using global using directives, you can keep your code files cleaner and more focused on the specific logic they contain, rather than being cluttered with repetitive using statements. This feature is particularly beneficial in large projects where certain namespaces are used universally.

Top comments (0)