C#7 – User’s Guide to Using

There have been some interesting improvements in how the using statement can be, erm, used, in C#7, which may be of interest to some.

To set the scene, let’s look at how we currently utilise them before moving onto the change which offers an alternative.

Imagine you want to print to the console window. To do that, ordinarily you have two options:

Specify all objects with full name spaces used:

It works just fine, but is a little bit of a typeful (rather than mouthful). A slightly better way introduces the usual using statement.

Use a using statement with System

For this, you would place this statement:

At the top of your C# file, and then reference objects like so:

Notice how you have to specify the public static class, Console, for this to work, but at least you avoid having to include the System part?

With C#7, there is a third way.

Using a static using statement

For this, we modify the using statement above ever so slightly, as follows:

Now, you can print to the console using the greatly reduced, but eminently readable:

Pretty nice, eh?

What would happen, though, if we removed the Console from the statement above?

As you can see, we need to reference a type and not just a namespace. In doing so, though, we can use ReadLine, ReadKey or any of the other Console members just as easily.

Time to get using!

twittergoogle_plusredditpinteresttumblrmail

Written by Stephen Moon
email: stephen at logicalmoon.com
www: https://www.logicalmoon.com


Leave a Reply

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