Creating a Utilities Class?

☆樱花仙子☆ 提交于 2019-12-03 09:51:18

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.

Lance

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, like Int32, 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

You will be better off using a static class with static methods. Then you won't need to instantiate your utilities class to use it. It will look something like this:

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

Then you can use it like this:

int result = Utilites.sum(1, 3);

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

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

public class Sum
{
    private int _result;

    public int Result {
       get {
           return _result;
       }
    }

    public Sum(int startNum) {
        _results = startNum;
    }

    public void Add(int num) {
        _result += num;
    }
}

And is called like:

Sum sum = new Sum(1);
sum.add(2);
int result = sum.Result;

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.

Rahul
  1. Create Utility class as public static class.
  2. Defined Utility function-method with static keyword

Method Calling :-

int result = Utilities.sum(1, 2);

   public static class MyMath
         {
             int result;

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

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

do this.

public static class Utilities
{
    int test;

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

That way you use it like

int result = Utilities.sum(1, 2);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!