DEV Community

Mark Clearwater
Mark Clearwater

Posted on • Originally published at on

Looking back on C# 6: Static Imports

Looking back on C# 6: Static Imports

With C# 8 on our doorstep, I wanted to go through some of the C# 6 and 7 language features I have been using that you may have missed.

Another feature that I avoided for a while, but have really starting to use a lot more. using brings a namespace into the scope of the file. This allows us to write Console.WriteLine("Hi"); instead of System.Console.WriteLine("Hi");. But with this language feature, we introduce a Static class into scope. So instead we could write WriteLine("Hi");. This looks a bit strange to start with because the code appears the same as calling a method in the current class (or base class).

The syntax to make this works is rather straight forward.

// This is a standard 'using'
using System;

// To pull in for the example above you would use the new syntax:
using static System.Console;

// But you can import any static class you like
using static MySystem.Helpers.LookupTables;

Used sparingly, this can reduce the noise in the code for strong domain concepts that you use everywhere, and improve readability as well as save keystrokes. The example always used is System.Math. but use this however best suits the domain you are working in.

As a language feature reaches a large enough common usage status, it becomes canonical in its usage. For me, this language feature has reached that point. Expect to see more of this strategically used in code going forward.

Top comments (0)