C# Anti-Pattern: Abusing Global Using Directives

Michael Moreno
3 min readAug 5, 2023

--

Sometimes new language features can engender new anti-patterns.

C# 10 introduced global using directives, a feature that allows developers to prepend any using directive with the keyword global. This has the effect of making the using directive accessible anywhere in the project.

Unfortunately, what I’ve seen is that developers will create a file named something like Global.cs and then dump every possible using directive they can into that file.

There are a couple problems with this:

  1. If you have types with the same names across different namespaces, the compiler will get confused about what’s what, and you’ll have ambiguous references. Sure, those can be fixed with using aliases, but it would be simpler to just not introduce the problem in the first place, would it not?
  2. The moment you start using this feature, it becomes impossible to reason about what namespaces a given file has access to simply by looking at the file.

Consider you have a file that looks like this:

namespace ConsoleApp
{
public class Program
{
public static void Main(string[] args)
{
var fooComponent = new FooComponent();

Console.WriteLine(fooComponent.Bar);
}
}
}

By just reading this file, there is no way to determine where FooComponent is coming from. Sure, your IDE might be able to tell you, but your IDE may not always be available. Maybe you’ll be reading the file from a web browser, for instance. This is a trivial example, with a single type and a twelve line program, but imagine your project has hundreds of files spread across a multitude of namespaces. Why make things hard on yourself? As developers, don’t we know that it’s better to be explicit? When did that principle go out the window? Just stick to defining the using directives your file has access to right at the top.

global using directives can be a useful feature, when used properly. I would suggest using them sparingly, for the most commonly referenced namespaces in your project only.

“But I don’t want so many using directives at the tops of my files!” you cry.

--

--