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?
Best is to make the functions not reliable to members of a class. Therefore you can make the functions static.
Better is to make the functions an extension method of a type. see here for example
yes this does not compile because int test which is not supported inside static class either make it as static int test which will be supported and returns the output
You should make it a
static
class, like this: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.do this.
That way you use it like
While new to OOP and trying to get a handle on best practices, it may be a good idea to try to avoid utility classes. You could redesign your class like
And is called like:
It'll be good practice until further experience with OOP can help you examine the trade-offs of using an utility class vs pure OOP principles.
If you are working with .NET 3.0 or above, you should look into extension methods. They allow you to write a
static
function that will act against a particular type, likeInt32
, while seeming to be a method on that object. So then you could have:int result = 1.Add(2);
.Try this out; it might just show you another way. ;)
C# Tutorial - Extension Methods