Using Directive With Keyword Static in C# 6.0

With C# 6.0, “using” directive is supported with Static keyword. The advantage of static keyword with using directive is that static methods would now be available in global scope i.e. static methods can be used without a type prefix of any kind.


System.Console is a static class and most of the methods from this class such as WriteLine, ReadKey are used with its type as in the following:

    Using System.Console;


New Approach:

    Using static System.Console;

This eliminates the need to qualify the static member with its type.

Pitfalls of using static

  1. Users must be very careful with the using static directive. They should take care of the fact that clarity of the code isn’t compromised.

    namespace myNameSpaceA
    1. internal static class A  
    2. {  
    3.    public bool CheckElement(int i)  
    4.    {  
    5.       return true;  
    6.    }  
    7. }  
    namespace myNameSpaceB
    1. Internal static Class B  
    2. {  
    3.    Public bool CheckElementAt(int i)  
    4.    {  
    5.       Return true;  
    6.    }  
    8. }  
    In main function:

    Using static myNameSpaceA
    1. TestMethod(int elementFromB)  
    2. {  
    3.    if(CheckElement()){ //;};  
    4. }  
    It may be misleading looking at the CheckElement which Class it belongs to. However, more explicitly, the call is from A. when, in fact, B. CheckElement is what’s needed here.

    Although the code is certainly readable, it’s incorrect and, at least in this case, it is advised avoiding the using static syntax is probably better.

    Well, another point to be noted is that if using static directives are written for both Class A and Class B, it would cause compilation errors while calling CheckElement.

  2. Extension Method:

    With C# 6.0, Extension methods aren’t moved into global scope as described above. First, extension methods are intended to be treated as instance methods on an object and it’s not a normal pattern to call them as static methods directly off the type.

    So enjoy using “static” with “using” but be careful and clear with your intentions.

Recommended Free Ebook
Similar Articles