Search code examples
c#staticalias

Define global alias for static classes


I have a static ExceptionHelper that looks like this:

public static class ExceptionHelper
{
    public static async void ShowDialog(string message)
    {
        // Show message
    }
}

Whenever I want to call this method I do it like this at the moment:

ExceptionHelper.ShowDialog("This is a message.");

I now thought of defining an alias for the ExceptionHelper to not having to write the whole word each time I want to use it.

I know I can achieve it with using:

using Ex = MyNamespaces.ExceptionHelper;

But then I'd have to define it in each file I want to use the method. Is there a way I can define the alias globally without changing the name of the class? Or is there any attribute I can set above the class declaration?


Solution

  • Extension Method

    You could make it an extension method on string.

    public static class ExceptionHelper
    {
        public static async void ShowDialog(this string message)
        {
            // Show message
        }
    }
    

    Then you would use it like so:

    using WhateverNamespaceExceptionHelperLivesIn;
    
    public class TestClass
    {
        public void TestMethod()
        {
            "This is a message".ShowDialog();
        }
    }
    

    This makes your question moot - you don't have to define an alias at all.

    Static imports

    An alternative approach is to import the class statically. You won't need an alias, because you can reference the ShowDialog method directly. This will require C#6/Visual Studio 2015.

    using static WhateverNamespaceExceptionHelperLivesIn.ExceptionHelper;
    
    public class TestClass
    {
        public void TestMethod()
        {
            ShowDialog("This is a message");
        }
    }