Search code examples
c#static-methodsutility-method

How can I call utility methods statically with a chain of classes?


I have a solution with a "Common" project. This "Common" project is used by other projects in the solution.

Within this "Common" project, I have a "Utilities" folder with several different utility classes, for example, "CsvUtilities.cs" and "JsonUtilities.cs". Assume that I could have many classes like this, and that all methods in these classes are pure functions. Based on this, it would make sense for these classes and methods to be static. Then from other projects I can import the common project and do things like:

CsvUtilities.StaticCsvMethod();
JsonUtilities.StaticJsonMethod();

This works and I think this is relatively normal.

Now the complication is that I want to create a hierarchy structure to access the static utility methods. I want to be able to type "Utilities." in the IDE and have intellisense show all existing utility classes, followed by all methods within that utility class.

So the code that I want would look like this:

Utilities.Csv.StaticCsvMethod();
Utilities.Json.StaticJsonMethod();

I implemented this idea by doing the following:

public static class Utilities
{
    public static CsvUtilities Csv { get; } = new CsvUtilities();
    public static JsonUtilities Json { get; } = new JsonUtilities();
}

However, there is a big problem with this solution. For this to work, the various utility classes and their methods must no longer be static, which is awkward for utility classes/methods.

I was not able to find an example of someone else doing something like this. What is the most reasonable way for me to use this "Utilities." structure while also keeping the utility classes/methods static?


Solution

  • You can use namespaces (or nested classes) to nest your calls like that. See following example

    namespace Utilities
    {
        public static class Json
        {
            public static void StaticJsonMethod()
            {
                // Do something
            }
        }
    }
    

    you can call that method using Utilities.Json.StaticJsonMethod().

    To add another level, you just append the "category" to the namespace:

    namespace Utilities.Formats
    {
        public static class Json
        {
            public static void StaticJsonMethod()
            {
                // Do something
            }
        }
    }
    

    you can call that method using Utilities.Formats.Json.StaticJsonMethod()