Creating a Utilities Class?

sooprise picture sooprise · May 18, 2010 · Viewed 47.5k times · Source

I'm very new to OOP and am trying my hardest to keep things strictly class based, while using good coding principles.

I'm a fair ways into my project now and I have a lot of general use methods I want to put into an utilities class. Is there a best way to create a utilities class?

public class Utilities
{
    int test;

    public Utilities()
    {
    }

    public int sum(int number1, int number2)
    {
        test = number1 + number2;
    }
    return test;
}

After creating this Utilities class, do I just create an Utilities object, and run the methods of my choosing? Do I have this Utilities class idea correct?

Answer

SLaks picture SLaks · May 18, 2010

You should make it a static class, like this:

public static class Utilities {
    public static int Sum(int number1, int number2) {
        return number1 + number2;
    }
}

int three = Utilities.Sum(1, 2);

The class should (usually) not have any fields or properties. (Unless you want to share a single instance of some object across your code, in which case you can make a static read-only property.