3

Today I was working on c sharp and I'm trying out static classes, but it doesn't seem to work for me and I would love to know the solution. I have been browsing around the web for a while now but I can't seem to find the answer.

Here is my code:

class Count
{
    public static int sum(int add1, int add2)
    {
        int result = add1 + add2;
        return result;
    }
}

class Program
{
   static void Main(String[] args)
    {
        Console.WriteLine("Adding: \nPlease enter the first number");
        int num1 = int.Parse(Console.ReadLine());
        Console.WriteLine("Please enter the second number");
        int num2 = int.Parse(Console.ReadLine());

        Count add = new Count();
        int total = add.sum(num1, num2);
        Console.WriteLine("The sum is {0}.", total);
        Console.ReadLine();
    }
}
Artifacialic
  • 51
  • 1
  • 2
  • 9

2 Answers2

10

sum is not an instance method, it must be accessed via its type. Replace this:

Count add = new Count();
int total = add.sum(num1, num2);

With this:

int total = Count.sum(num1, num2);
Charles Mager
  • 25,735
  • 2
  • 35
  • 45
5

If you're trying to use static classes - mark the Count class as static - like so:

public static class Count

and then use the following in your code:

int total = Count.sum(num1, num2);

And it should work as expected.

Jared Kove
  • 235
  • 1
  • 13
  • 1
    he does say `static classes`, so he does probably want that. But whether or not `Count` is static doesn't affect how he should call `sum` – Jonesopolis Apr 03 '17 at 12:36
  • @Jonesopolis Correct, it just saves him marking every method as static if he described what he was trying to achieve correctly - Worth noting however. – Jared Kove Apr 03 '17 at 12:37