Simplify Static Member Access – Using Statement With Static Classes in C# 6.0

By | November 25, 2014

C# 6.0 introduced many small and useful features that helps developers to write clean code. On of such feature is “Using Statement with Static Classes”. We know a static class cannot be instantiated. While using any static member, we find ourselves repeating the class name to access any of the static members. It looks kind of redundant which is unnecessary.

For an example,  Console is Static Class, and following is a code snippet that shows a small example on how we can use different member of Console class.

static void Main(string[] args)
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Enter Something");
string readKey = Console.ReadLine();

It is very obvious and noticeable, we are repeating the Console class to get the access to the members, as it does not have any reference.  C# 6.0, allows us to avoid this code repetition, just adding Using with the Static Class. And following code demonstrate the same.

using System.Console;
static void Main(string[] args)
ForegroundColor = ConsoleColor.Red;
WriteLine("Enter Something");
string readKey = ReadLine();

Both the code blocks will produce same output, where as the second one with the namespace of static class referred, code looks more clean. This was just a simple example, there are multiple static classes are defined in .NET Framework. Also think about the number of helper classes we generally write for simplify some of the code modules and defined them as static, in this case, they can be called in a very clean way.


Note : When there is an ambiguity in reference, which mean multiple class having the same method defined, you need to refer them along with class name. For an example, you need call Console.Clear(), if any other class having same method definition.