Order of Using Directives in C#

There are many things in software development that have ignited holy wars over the years. Stored procs vs ORMs. Tabs vs spaces. Emacs vs Vi. You name it and software developers have most likely argued about it.

This post isn’t meant to start another holy war, but I’ve had a couple conversations about it the last few months that sort of surprised me: the order of using directives to include namespaces in C# code.

Let me start by saying that I like alphabetical order. I usually put the methods in my classes in alphabetical order, and many times I order configuration settings the same way. But that’s not what I do with using directives, sort of. Allow me to explain.

Context and Scope

I’m a fan of context and scope, and I believe using directives should be applied based on scope. And in the context of using directives, scope falls into three groups (from widest to narrowest):

  • System
  • 3rd party libraries
  • Your application

This is how using directives should be ordered, but with one caveat: within each of those groups, using directives should be alphabetized.

Using Directives, Wrong

Here’s a listing of using directives that I believe is wrong:

It has 7 using directives, in simple alphabetical order, but it starts with namespaces from MyApp, then references NHibernate (3rd party library), then pulls in a couple system namespaces, and lastly includes the Twilio client, another 3rd party library. Seems disorganized to me.

Using Directives, Correct

Let’s take those same 7 using directives and apply the context and scope I mentioned above:

Here we’ve got system directives followed by 3rd party directives followed by application-specific directives. To me it just *feels* better.

Visual Studio Settings

Visual Studio (in my case, version 2013) has an option to help with this located at Tools > Options > Text Editor > C# > Advanced:

vs-system-sorts

Simply check the Place ‘System’ directives first when sorting usings option in the Organize Usings section.

Summary

Ultimately, the order in which namespaces are included in C# code doesn’t mean much. I get that. But in the particular case of using directives, context and scope feel more important than blindly listing them in alphabetical order.

Featured Image: Some rights reserved by sjrankin

Leave a Reply

Your email address will not be published. Required fields are marked *