Search code examples
c#utility-method

C# Utility Class - Setting up for General Use and Compiling w/o Main


Okay, so working on learning some C#. Great language, love working with it in general, but I'm not understanding how to get over this lack of utility classes. In essence, I want to set up a general utilities class that can be contained in a folder and used for any project simply by doing a "using namespace Globals/Utilities/etc." command. In essence:

using System;
namespace Globals {
    public static class Commands {
        public static void WaitForReturn() {
            Console.WriteLine("Press Enter to continue.");
            Console.ReadLine();
        }
    }
}

Similar to the above, such that in any other class I can call the functions by including it as a preprocessing directive.

using System;
using Globals;

namespace RectangleDemo {
    <rectangle definition here>

    class Demo {
        static void Main(string[] args) {
            Rectangle r = new Rectangle();
            Rectangle s = new Rectangle(5, 6);
            r.Display();
            s.Display();
            WaitForReturn();
        }
    }
}

As it is, I'm trying to simply compile my 'utility' class (with more than what is listed above) to check for errors, but it's just telling me that it can't compile it because there's no main method. Any suggestions?

(Yes I'm aware I have a java coding style, I'm okay with that!)


Solution

  • C# doesn't work the way you're expecting. There is no relationship between importing namespaces/classes and files so doing using Globals; does not translate to file content inclusion à la C/C++ (i.e. not the same as #include "Globals.cs").

    On the command line, the C# compiler accepts the list of files that make up your sources:

    csc Demo.cs Globals.cs
    

    If you are using an IDE like Visual Studio, you would link the Globals.cs into your project. And by link, I mean more like a symbolic link (though it is not in actual fact) than static linking via a linker as you would have typically in a C/C++ setup.

    So to make your scenario of “inclusion of common code” work, you need to compile by simply always adding Globals.cs to the list of C# files making up your project (supplied to the compiler on the command line or added to your project in IDE) and then using a static import:

    using System;
    using static Globals.Commands; // <-- import statically allows methods to be
                                   //     used without class name qualification
    
    namespace RectangleDemo {
        // <rectangle definition here>
    
        class Demo {
            static void Main(string[] args) {
                Rectangle r = new Rectangle();
                Rectangle s = new Rectangle(5, 6);
                r.Display();
                s.Display();
                WaitForReturn();
            }
        }
    }