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);
}
}
}

--

--

Michael Moreno
Michael Moreno

No responses yet