Intro

Did you know that static classes can be inferred when invoking static methods, properties, and/or fields from another class? To do this, we declare a static class in the using statements of a client class.

Public static Methods

To demonstrate the need for this feature, let’s create a static class called MessageBus:

namespace Tests.Messaging
{
    public static class MessageBus
    {
        public static void Subscribe(string message) { }
        public static void Publish(string message) { }
    }
}

Public Static Field

Let’s next create a static class called Messages:

namespace Tests.Messaging
{
    public static class Messages
    {
        public static string SOME_MESSAGE = "SOME_MESSAGE";
    }
}

Explicit Static Class Reference

Note how we reference the static classes in order to invoke a static method and field variable on a client to the classes.

        [TestMethod]
        public void some_test1()
        {
            // Test
            MessageBus.Subscribe(Messages.SOME_MESSAGE);
        }

However, we don’t have to be this explicit. Hence, we can reduce the verbosity of this syntax by leveraging the “Using Static” declaration.

Removing the Cruft

When we declare a static class in the usings section of our csharp file, the compiler will enable us to just call the static method, member, and/or property of the static class. Therefore, we do not have to specify the class name in order to invoke it’s member.

Consider the following code:

using Microsoft.VisualStudio.TestTools.UnitTesting;
using static Tests.Messaging.MessageBus;
using static Tests.Messaging.Messages;

namespace Tests
{
    [TestClass]
    public class MyTest
    {
        [TestMethod]
        public void some_test1()
        {
            // Test
            Subscribe(SOME_MESSAGE);
        }
    }
}

Ahh… The above code is much more readable than the previous version. Hence, we no longer have to provide the class name that owns the static member. Instead we just specify the static member by itself. Thus, the code (aka: business logic) is simple compared to the previous version.

We accomplished this by providing the following using statements:

using static Tests.Messaging.MessageBus;
using static Tests.Messaging.Messages;

Thus, that’s how we can simplify this:

MessageBus.Subscribe(Messages.SOME_MESSAGE);

to this:

Subscribe(SOME_MESSAGE);

Conclusion

In conclusion, static classes can be inferred when invoking static methods, properties, and/or fields from another class? To do this, we declare a static class in the using statements of a client class.

Advertisements