Author avatar

Kirk Larkin

Simplifying References to Static Members in C# with Using Static

Kirk Larkin

  • Sep 18, 2019
  • 8 Min read
  • 68 Views
  • Sep 18, 2019
  • 8 Min read
  • 68 Views
Languages Frameworks and Tools
C#

Introduction

In this guide, we're going to talk about referencing C# types and simplifying how we reference them with using directives and, the newer, using static directive. We'll start with a recap of how we reference types without using directives and how a using namespace directive can both simplify C# code and improve its readability. We'll continue on to discuss the using static directive where we'll look at a few examples of what it is and how it can further simplify C# code. Finally, we'll consider how the using static directive affects the readability of the C# code we write.

Qualifying References to C# Types with a Namespace

The following example uses Console.WriteLine to write two lines to the console. When resolving references to the Console class, the C# compiler needs to know which namespace it's in. We tell the compiler that the Console class we want to use is in the System namespace by qualifying references to it with this namespace:

1
2
System.Console.WriteLine("C# is awesome.");
System.Console.WriteLine("Pluralsight Guides make C# even more awesome.");
csharp

Now the compiler knows exactly where to find the Console class, but we've had to tell it twice. If we add more calls to Console.WriteLine, we're going to have to tell the compiler again and again that the Console class we want to use is in the System namespace.

The using Directive

Rather than specifying System.Console everywhere that we reference the Console class, we can introduce a using directive for the System namespace:

1
using System;
csharp

A using directive makes the types from a namespace available without requiring references to be qualified with the namespace. For our example using the Console class, this means that we no longer need to qualify references to the class with its System namespace:

1
2
Console.WriteLine("C# is awesome.");
Console.WriteLine("Pluralsight Guides make C# even more awesome.");
csharp

Even with just this small change, we've already simplified the code and made it a bit more readable. We've stopped repeating ourselves too. Well, we've stopped repeating System., but can we also stop repeating Console.?

The using static Directive

With its release in 2015, C# 6 introduced the using static directive. This directive allows us to reference static members without needing to reference the namespace or even the type itself.

using static directives can also be used to reference nested types.

The WriteLine method that we've been using in our examples is a static member of the Console class. Let's look at an example of how a using static directive can further simplify references to Console.WriteLine:

1
using static System.Console;
csharp

With this directive in place, we can reference static members of the Console class without even referencing the class itself:

1
2
WriteLine("C# is awesome.");
WriteLine("Pluralsight Guides make C# even more awesome.");
csharp

This results in simpler code, with even less repetition than in the previous example. We've gone from using Console.WriteLine down to just using WriteLine, but is this more readable than the previous example? Before we discuss readability, let's take a look at a more complete example.

Example: Super Awesome Base64 Encoder

Imagine we've been tasked with writing a small C# program that prompts the user for a string and writes it back to the console encoded as a Base64 string. Without using static directives, we come up with the following solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using System;
using System.Text;

class Program
{
    static void Main()
    {
        Console.WriteLine("--- Super Awesome Base64 Encoder ---");
        Console.Write("Enter a string to encode: ");

        var userInput = Console.ReadLine();

        Console.WriteLine(Base64Encode(userInput));
    }

    static string Base64Encode(string str)
    {
        var strBytes = Encoding.UTF8.GetBytes(str);
        var strBase64 = Convert.ToBase64String(strBytes);

        return strBase64;
    }
}
csharp

We run our program, enter a string of "I love Pluralsight Guides", and watch with joy as the Base64 encoded version of our string is displayed back to us using our favorite Console class:

1
2
3
--- Super Awesome Base64 Encoder ---
Enter a string to encode: I love Pluralsight Guides
SSBsb3ZlIFBsdXJhbHNpZ2h0IEd1aWRlcw==

Now that we know about this using static directive thing, we introduce it for System.Console and remove all traces of Console. from the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
using System;
using System.Text;
using static System.Console;

class Program
{
    static void Main()
    {
        WriteLine("--- Super Awesome Base64 Encoder ---");
        Write("Enter a string to encode: ");

        var userInput = ReadLine();

        WriteLine(Base64Encode(userInput));
    }

    static string Base64Encode(string str)
    {
        var strBytes = Encoding.UTF8.GetBytes(str);
        var strBase64 = Convert.ToBase64String(strBytes);

        return strBase64;
    }
}
csharp

With this change, we've simplified references to Console.WriteLine, Console.Write, and Console.ReadLine. Instead, we just reference WriteLine, Write, and ReadLine respectively. We could do the same for Encoding.UTF8 and Convert, but this brings us back to the question of readability. Have we made the code more readable? Have we somehow ended up making the code less readable?

Readability

When we went from System.Console.WriteLine to Console.WriteLine, the code became a bit more readable. When we see Console.WriteLine, we might already know that Console is in the System namespace. Even if we don't know this, it's still clear that Console.WriteLine is going to write a line to the console.

When we went from Console.WriteLine to WriteLine, did the code become even more readable? Is it reasonably clear that WriteLine writes a line to the console? This is more of a subjective question. There's no right or wrong answer here. When writing code with using static directives, we need to consider the context in which the code runs. In the context of the Main method in a console application, it might be reasonably clear that WriteLine is going to write to the console. It might not be.

For some types, using static directives are more readable than others. Here are a few examples for consideration:

  • Environment.GetEnvironmentVariable("PATH") can become GetEnvironmentVariable("PATH").
  • String.Concat("Pluralsight", " ", "Guides") can become Concat("Pluralsight", " ", "Guides").
  • File.OpenRead("/path/to/file") can become OpenRead("/path/to/file").

As we've already said, there are no right or wrong answers here. Consider the examples above and make your own decisions as to whether or not they make your code more or less readable. If you're working on a team, discuss some of the examples with your teammates and try to come up with an idea of what readability means to your team.

Conclusion

The using static directive simplifies references to static members and nested types by allowing us to write less code. Use it with caution. Careful use of the directive can certainly improve the readability of the code we write, but be sure to consider the context in which you use it to avoid running the risk of writing less readable code.

To learn more about using directives, see the following links:

2