#1,214 – C# 6.0 – using Directive with Static Class

In C# 6.0, you can use a using directive not only with namespace names, but also with the name of a static class.  This allows invoking static methods in the class without having to specify the class name.

For example, assume that we have a static class Utility with an AddInts method.  Assume also that Utility is defined within a namespace having the name SomeNamespace.  In C# 5.0, you’d do the following to call the method:

using System;
using SomeNamespace;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int sum = Utility.AddInts(5, 2);

            Console.ReadLine();
        }
    }
}

In C# 6.0, you can include the class name in the using directive and omit it when invoking the method.

using System;
using SomeNamespace.Utility;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int sum = AddInts(5, 2);

            Console.ReadLine();
        }
    }
}

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #1,214 – C# 6.0 – using Directive with Static Class

  1. Pingback: Dew Drop – October 29, 2014 (#1887) | Morning Dew

  2. You could go one step further with this:

    using System;
    using System.Console;
    using SomeNamespace.Utility;

    namespace ConsoleApplication1
    {
    class Program
    {
    static void Main(string[] args)
    {
    int sum = AddInts(5, 2);

    ReadLine();
    }
    }
    }

Leave a comment