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

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

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.Clear();
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Enter Something");
string readKey = Console.ReadLine();
Console.WriteLine(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)
{
Clear();
ForegroundColor = ConsoleColor.Red;
WriteLine("Enter Something");
string readKey = ReadLine();
WriteLine(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.

Abhijit Jana

Abhijit runs the Daily .NET Tips. He started this site with a vision to have a single knowledge base of .NET tips and tricks and share post that can quickly help any developers . He is a Former Microsoft ASP.NET MVP, CodeProject MVP, Mentor, Speaker, Author, Technology Evangelist and presently working as a .NET Consultant. He blogs at http://abhijitjana.net , you can follow him @AbhijitJana . He is the author of book Kinect for Windows SDK Programming Guide.