Using Static Directive?

Admittedly, the title of this article reads somewhat awkwardly. For the sake of improving clarity it could instead be, Using Statics in a Using Directive. However, I find the oddly compressed wording of the title fitting as its spartan use of terms bear similarity to the subject of the article; adding using directives to static classes in order to streamline code references to static members.

The Using Directive

In C# the using keyword has two forms:

What is the difference between a using Statement and a using Directive?
For our purposes here a using Statement is compiled into the resulting CIL as a try/finally block

A using directive however, is a directive so doesn’t get compiled. Rather it directs the compilation process.

Without including using directives one would write:

By adding the following using directive one tells the compiler to include the System.Text namespace when trying to resolve references

allowing one to instead write:

The using directive can also direct the compilation process in a manner to allow aliases to be used for specific namespaces. This is done either to shorten unweildy names, improve clarity of code, or most commonly to avoid name collision. An example of the latter should suffice to illustrate the set.

Starting with our earlier example using StringBuilder let’s assume one needs to make use of an external precompiled library containing one namespace of interest, Confusion.StateOf.Text and said namespace contains a class named StringBuilder that is not compatible with the one in System.Text; to make matters more difficult one needs to use both System.Text.StringBuilder and Confusion.StateOf.Text.StringBuilder in the same CSharp source file (there are other ways to handle this).

In order to deal with ambiguity surrounding StringBuilder references one could write in the following manner:

The code’s pretty clear, if not a bit unwieldy. The potentential for confusion exists as these two disparate StringBuilders get passed around. The inclusion of a using alias directive helps.

The code reads a bit better and is a bit shorter; System.Text is one of the shortest to start. Now consider if the namespaces were either deeper or very similar such as System.Collections.Specialized and Confusion.StateOf.Collections.Specialized and the benefits are clearer; even more so if one accounts for the occasional truncation of fully qualified names due to display limitations during debug.

Using Static Directive

A using Directive references a namespace or a namespace along with an alias for it. As of C# 6 using Directives can also reference Static types. This fits very well with the existing paradigm of using Directives in C#, more succintly using Directives reduce or eliminate the need to explicitly declare the non-instance portion of a type.

Static classes don’t have instance members. Given this the non-instance specific portion of a static class’s member includes the static class name.

System.Text.StringBuilder is in the namespace, System.Text, which is its non-instance portion. Any deeper requires an instance of StringBuilder. But we can eliminate having to include the non-instance portion, System.Text, in references to StringBuilder by including, using System.Text;

System.Math is a static class containing numerous static methods and constants. System is its namespace and by including, using System; we can shorten our reference its members from System.Math… to Math… e.g. System.Math.Pi to Math.Pi.
Static types can’t have multiple instances; there’s one instance whose lifetime is managed by the runtime and available without instance reference. There’s no var myMath = new Math(); This means the non-instance portion of its fully qualified name isn’t System it’s System.Math. As of C# 6 we can take advantage of similarity because C# now supports the Using Static Directive.

System.Math contains two Fields, the constants Pi and E of type System.Double;

Historically, one has needed to include the static type. e.g.

With C# 6 by including

one can instead write

The result is less noisy and arguably clearer.

Where would one use this?

A good use would be corralling extension methods. Extension methods are static methods which extend the functionality of a given and different type. Additionally extension methods must be part of a static class. Extension methods are useful and their ease of consumption makes creating and using them overly attractive. Without care they become spread about and become hard to track. With using static one can be a bit more specific about which ones to include or not.

In previous versions of C# we’d need to add a using SillyExtensions; directive and DoSilly() would be available to all String instances within the file.

What if another class with a DoSilly extension method was added; one which we’d prefer to be used instead?

If we needed the keep the original the using SillyExtensions; Directive due to the additional functionality a different contained class, NeedTheseExtensions, exposed, we would have a name collision issue on DoSilly(this String self).

If we convert our using directives to using static directives we’ll eliminate the collision (assume added to the same SillyExtensions namespace for convenience) and be explicit about which extension class we would like invoked.

Extension method ambiguity is gone and we are quite explicit about which classes we are using for extension methods.

Are there gotchas?

Like with any good tool, there most certainly are.

Name collision among static types resulting in ambiguous references is one potential pitfall.

Also, using static will import the referenced static type’s methods along with any nested types, but not inherited members are not imported.

The new Using Static Directive is useful in lowering the overall noise level when using static types and to specify which static types within a namespace are to be imported.