James Michael Hare

...hare-brained ideas from the realm of software development...
posts - 166 , comments - 1494 , trackbacks - 0

My Links

News

Welcome to my blog! I'm a Sr. Software Development Engineer in the Seattle area, who has been performing C++/C#/Java development for over 20 years, but have definitely learned that there is always more to learn!

All thoughts and opinions expressed in my blog and my comments are my own and do not represent the thoughts of my employer.

Blogs I Read

Follow BlkRabbitCoder on Twitter

Tag Cloud

Archives

Post Categories

.NET

CSharp

Little Wonders

Little Wonders

vNext

C#/.NET Little Wonders: Static Using Statements in C# 6

Once again, in this series of posts I look at the parts of the .NET Framework that may seem trivial, but can help improve your code by making it easier to write and maintain. The index of all my past little wonders posts can be found here.

Visual Studio 2015 is on the horizon!  In fact, some of you may already have played with the preview and seen some of the many neat new things to come – both in the IDE and in the C# language.

For those who haven’t been keeping up with the announcements, I’m taking some blog time for a few Little Wonders posts to talk about some of the neat new things that will be in C# 6. 

Note: All of the C# 6 features mentioned are current with the latest CTP of VS2015 as of the time of this writing.  The syntax and exact feature behaviors may be subject to change in the final released version.

Importing a whole namespace with “using”

Of course, we all know that you can import a namespace with using.  This gives us the ability to use a type with just the type’s name in our code.  That is, it allows us to use the type name directly without the need of fully qualifying it with it’s namespace.

For example, if we didn’t import the System namespace, we’d have to say:

public class Driver
{
    public static void Main()
    {
        // without importing a namespace, we'd have to fully qualify the type
        // Console as System.Console
        System.Console.WriteLine("Hello, World!");
    }
}

But, of course, we can import the System namespace, so that allows us to shorten the call to just:

using System;
 
public class Driver
{
    public static void Main()
    {
        Console.WriteLine("Hello, World!");
    }
}

This eliminates a lot of redundant “System.” prefixes in our code.  But this is all old stuff, why bring it up?  Mostly, I wanted to set the stage for what using does today so I can discuss what changes have been made with the new using static directive in C# 6.

Importing a static class with “using static”

Now, in C# 6, we can go one step further and import the static members of a class into our namespace.  This means we can use the static members of a class directly with no need to qualify them with their namespace or type name!

The format is “using static” followed by the type whose static methods you wish to import.  For example, our short example before now becomes:

using static System.Console;
 
public class Driver
{
    public static void Main()
    {
        // Now, the System.Console static class is imported, so we
        // can use WriteLine directly
        WriteLine("Hello, World!");
    }
}

This may seem trivial, but it can eliminate a lot of redundant or superfluous type identifiers in the code and thus help improve readability (if used appropriately). 

Note: In previous previews, the format was simply using without the static keyword, and only worked on static classes.  In the current preview, the format has changed to using static and can import static members of any type (class, struct, enum).

Think, for example, of static classes like Math where it is simply a collection of mathematical functions.  The “Math.” prefix really doesn’t add much to the readability because we know Sqrt() is a math function, so we can drop it with a using static System.Math like this:

using static System.Console;
using static System.Math;
 
public class Driver
{
    public static void Main()
    {
        // Now we can access Sqrt directly since we imported System.Math
        WriteLine("Hello, World: the square root of 4 is " + Sqrt(4));
    }
}

Or consider static classes like Enumerable that have a lot of nice static methods like Range() and Repeat().  Again the “Enumerable.” prefix doesn’t add much to the readability, so why not drop it with a static import?

using static System.Linq.Enumerable;
 
public class Driver
{
    public static void Main()
    {
        // Now, Enumerable.Range() can just become Range()
        var nums = Range(1, 10).ToArray();
 
        ...
    }
}

As you can see, this shortens the body of our code and eliminates unnecessary identifiers.  Obviously, you’ll want to use this with care.  There are probably some instances where including the type name improves readability (that is, if you can’t easily tell the original of the method without it from the context).  As such, make sure you use good judgment on when it improves readability and when it doesn’t.

Limiting Extension Method visibility with “using static”

Here’s one very big reason I’m excited about using static: I love extension methods.  I do not love abusing them, but I do love well designed extension methods and think they can really improve your code if used judiciously.  The problem with extension methods is that even the well-written ones can pollute your namespace (and IntelliSense) if you have a lot of them extending some of the more common types (like string or object).

One way to limit this impact would be to put your extension methods into very compartmentalized namespaces and only import the namespace you want.

For example, let’s say I have a namespace called Utilities.Extensions and under it I have extensions for:

  • Preconditions – extensions to allow me to create test preconditions much like Google Guava in Java
  • Strings – extensions to allow me to check strings for certain formats
  • Typeextensions for querying properties of types
  • etc.

If all of these static classes with their extensions were in the same namespace, and I did an import such as:

// imports the whole namespace including all extension methods
using Utilities.Extensions;

Then all of the extension methods becomes implicitly visible whether I want them or not.  It would be nice to isolate them.  So I could put each of the static classes in their own namespace, but then I’d have namespaces for Utilities.Extensions.Preconditions just to hold a Preconditions static class, which seems a bit redundant.

Instead, I can now take advantage of using static and just include the extension methods from the class that I want, which will only make those extension methods visible without an explicit reference:

// only Preconditions and it's extension methods will be visible
using static Utilities.Extensions.Preconditions;

Now, only the extension methods in Preconditions will be visible without an explicit reference, and all the other extension methods in Utilities.Extensions will not be imported.

Importing enum constants with “using static”

As I alluded to before, in the current preview you can also import the static members of any type, not just static classes.  This means you can import the constants of an enum (static by definition) so you do not need to explicitly qualify them.

Consider if you wanted to do a lot of console output with multiple colors.  You’d make use of the System.Console class and the System.ConsoleColor enum.  This would mean that you’d have to use a lot of code like:

Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("This is my output in red");
 
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("This is my output in white");
 
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine("This is my output in blue");

Now, we know we can eliminate the “Console.” with a using static System.Console, but we can also eliminate the need to qualify the constants of the enum by performing a using static System.ConsoleColor as well, this would shorten it to:

ForegroundColor = Red;
WriteLine("This is my output in red");
 
ForegroundColor = White;
WriteLine("This is my output in white");
 
ForegroundColor = Blue;
WriteLine("This is my output in blue");

This eliminates a lot of very redundant qualifiers that don’t really improve the quality of the code.

Summary

The new using static directive allows us to import the static members of a type without needing to qualify them with their type name.  This can help improve readability and maintainability in your code.  Of course, as with any syntactical sugar, you should be careful not to abuse this power.  If the addition of the qualifying type name actually improves the readability of the code, then by all means keep it.  But for cases where the qualifying type name becomes redundant or superfluous, feel free to utilize the new using static to eliminate the need to explicitly state it.

Thanks for reading and stay tuned for more features of C# 6!

Print | posted on Thursday, April 16, 2015 8:14 PM | Filed Under [ My Blog C# Software .NET Little Wonders vNext ]

Feedback

Gravatar

# re: C#/.NET Little Wonders: Static Using Statements in C# 6

Not sure i like this feature at all.

I think it degrades the reading experience. How am i to know when looking at code without an IDE whether the Method is in the current class, the base class or from something imported?
4/17/2015 7:55 AM | Liam
Gravatar

# re: C#/.NET Little Wonders: Static Using Statements in C# 6

@Liam: I definitely agree that there is a potential to make code more confusing with this. It's similar to me with extension methods where it does end up hiding the type the member is part of.

That said, I can see it being helpful as well for things that are much more repetative and obvious.

And, to be fair, this is a feature Java recently added as well ("import static") so it could be a case of "keeping up with the Jones's". That said, I do really like this feature's ability to limit which extension methods you are importing from a namespace.
4/17/2015 8:48 AM | James Michael Hare
Gravatar

# re: C#/.NET Little Wonders: Static Using Statements in C# 6

ForegroundColor = Red;

This code actually is a good example for a misuse of this feature. From this piece of code you can't tell what it does. The fact that this is the 2nd best example that you have shows that this feature is not needed in the language. Pretty much the only good example I have seen is the Math class because the method names are truly globally unique. No other class has globally clear names.
4/17/2015 1:46 PM | mark
Gravatar

# re: C#/.NET Little Wonders: Static Using Statements in C# 6

@Mark:

I actually half-disagree. If my class was dedicated to console output, then I think it would be a fair assumption that ForeGround and Red refer to the console. Yes, as I said, it's possible to abuse this feature. But I really think it's all about the context in which you use it and whether you can reasonably infer (or even care) where the static member is from.

Unfortunately, it's hard to write a perfect example without a lot of code context that would obfuscate the example. So yes, this is somewhat trivial, that's why I tried to put it out there with a grain of salt to "use it where it makes sense".
4/17/2015 1:52 PM | James Michael Hare
Gravatar

# re: C#/.NET Little Wonders: Static Using Statements in C# 6

The harm of adding "Console." is extremely small. It's just unnecessary to strip it. Can you point to any good example use case for this feature other than Math? Math is a good case because the method names can stand for themselves.

I really mean this literally. Can you give *any* other example? I can't think of any.
4/17/2015 2:03 PM | mark
Gravatar

# re: C#/.NET Little Wonders: Static Using Statements in C# 6

@Mark: Truly, I understand your trepidation. I felt the same way the first time I saw "import static" in Java (which this feature is somewhat a copy of).

Now, to your point, it may be unnecessary to strip Console, but neither is it necessary to retype it over and over if the intention is clear. It's all syntactical sugar, after all.

Math is a classic example, and I'd argue Enumerable is another (allows you to type Range() instead of Enumerable.Range(), similarly for Repeat, etc.

However, I would *not* use this for something like Tuple.Create() since Create() by itself carries no context whatsoever. This is why I say it should be judiciously applied.

And, like I said, it doesn't just give you the ability to strip the type qualifier, it also gives you the ability to isolate which extension methods that are imported into your namespace which I find *extremely* valuable.
4/17/2015 2:17 PM | James Michael Hare
Gravatar

# re: C#/.NET Little Wonders: Static Using Statements in C# 6

The funny thing is, I knew when I was writing this post that it was going to be a "love it " or "hate it" thing. Much like extension methods.
4/17/2015 2:21 PM | James Michael Hare
Gravatar

# re: C#/.NET Little Wonders: Static Using Statements in C# 6

James,

I love your blog, I have your feed. I constantly get duplicates in my feed... I'm not sure if your editing stuff and modifying the unique identifier or what. I read through feedly, but I recall the same issue back when using google reader.

I'm not sure if others see the same thing, but it's been a cronic problem with this blog so I thought I'd mention it.
5/15/2015 9:47 AM | PilotBob
Gravatar

# re: C#/.NET Little Wonders: Static Using Statements in C# 6

@PilotBob, I have heard that once before. When I push updates it usually takes the place of the old blog, so not sure why it's duplicating.

Thanks for reminding me, though, I'll see if I can find out what's happening.
5/15/2015 12:37 PM | James Michael Hare
Gravatar

# re: C#/.NET Little Wonders: Static Using Statements in C# 6

Many similar objections were given when introducing the var keyword and type inference. Some people in my team still prefer:

bool s = GetActiveStatus(user);

to

var isActive = GetActiveStatus(user);

In console/terminal apps, I'm importing System.Console and MyApp.Console. Write, WriteLine, ReadLine, ReadBoolean. Who cares where they're coming from if its usage is obvious.
11/15/2016 4:18 AM | Erik E. van Vliet
Gravatar

# re: C#/.NET Little Wonders: Static Using Statements in C# 6

I find this very very appealing!! I even started laughing out loud with joy thinking that I wouldn't have to write String.IsNullOrWhiteSpace() every single time I use the method, which in my project is used numerously.
3/23/2017 8:42 AM | Suhail
Gravatar

# re: C#/.NET Little Wonders: Static Using Statements in C# 6

Love it! I write a LOT of console utilities, POC's etc. and not having to type Console all the time is worth it alone.

Var I think should be limited to LINQ queries as much as possible, was not happy when they brought it out and I think it gets abused a LOT.
7/28/2017 6:21 AM | Richard Wickens
Post A Comment
Title:
Name:
Email:
Comment:
Verification:
 

Powered by: