C# 6.0 – Using Static

[7/30/2015] This article was written against a pre-release version of C# 6.0. Be sure to check out the list of my five favorite C# 6.0 features for content written against the release!

In this installment of my ongoing series covering likely C# 6 language features I’ll be covering one of the features listed as “Done” on the Language feature implementation status page: using static. The idea behind using static is to allow importing members from static classes thus removing the requirement to qualify every member of an imported class with its owner. For the F#ers reading this, using static brings open module to C#.

Consider a method that writes some text to the console:

public void DoSomething()
{
  Console.WriteLine("Line 1");
  Console.WriteLine("Line 2");
  Console.WriteLine("Line 3");
}

In this example, we’ve had to specify the Console class three times. The using static feature we can simply invoke the WriteLine method:

using System.Console;

public void DoSomething()
{
  WriteLine("Line 1");
  WriteLine("Line 2");
  WriteLine("Line 3");
}

The primary benefit in this contrived example is eliminating redundancy but consider a more practical example which makes use of some of System.Math’s members:

class Circle(int radius)
{
  public int Radius { get; } = radius;

  public double GetArea()
  {
    return Math.PI * Math.Pow(Radius, 2);
  }
}

Here we’ve had to qualify both PI and Pow with the Math class. Granted, it only appears twice when calculating the area of a circle but it’s easy to imagine the amount of noise it would generate in more complex computations. In these cases, using static is less about eliminating redundancy and more about letting you stay focused on the problem as you can see in this revised example:

using System.Math;

class Circle(int radius)
{
  public int Radius { get; } = radius;

  public double GetArea()
  {
    return PI * Pow(Radius, 2);
  }
}

With both references to the Math class removed from the GetArea function, its much more readable.

I have to admit that I’m pretty excited about this feature. I can see it going a long way toward making code more maintainable.

Advertisements