#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();
        }
    }
}
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: