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:
System.Console.Writeline(“Hello from Option 1”);
It works just fine, but is a little bit of a typeful (rather than mouthful). A slightly better way introduces the usual using statement.
For this, you would place this statement:
At the top of your C# file, and then reference objects like so:
Console.WriteLine(“Hello from Option 2”);
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.
For this, we modify the using statement above ever so slightly, as follows:
using static System.Console;
Now, you can print to the console using the greatly reduced, but eminently readable:
WriteLine(“Hello from Option 3”);
Pretty nice, eh? What would happen, though, if we removed the Console from the statement above?
using static System;
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!
Hi! Did you find this useful or interesting? I have an email list coming soon, but in the meantime, if you ready anything you fancy chatting about, I would love to hear from you. You can contact me here or at stephen ‘at’ logicalmoon.com