Sunday, 4 October 2015

C# 6.0 – USING STATIC

 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:
1
2
3
4
5
6
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:
1
2
3
4
5
6
7
8
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:
1
2
3
4
5
6
7
8
9
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:
1
2
3
4
5
6
7
8
9
10
11
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.

No comments:

Post a Comment