I'm learning C# coming C and I'm having probelms with this basic code getting the error
"an object reference is required from a non-static field, method or property 'ConsoleApplication1.Program.Addtion(int, int)'"

on the line 14

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int ia = 10;
            int ja = 20;
            int answer = Addtion(ia, ja);
            if (answer == 0)
                Console.WriteLine("Number Over or Equal to 100");
            else
                Console.WriteLine(answer);
        }

        public int Addtion(int number1, int number2)
        {
            int result = number1 + number2;
            if (result >= 100)
            {
                return result;
            }
            return 0;
        }
    }
}

Please Help :(

Recommended Answers

All 2 Replies

In C# static means no need for instantiation.

Inside a static method (Main) you ar calling a non static function Addtion. According to the C# rules, you need to declare Addtion as static like

static public int Addtion(int number1, int number2)

Hope this helps

Line 21 you declare the method Addtion. Notice that the accessors are 'public'. Now take a look at the method Main. Its accessors are 'static'. This is where your problem lies.

Methods that are static are used by using the class name and the method. Using your code as an example, it would be Program.Main. Inside of a static method you can refer to other static methods of that class without needing to prefix it with the class name.

Instance methods, which Addtion is an example of, need you to instantiate the class and refer to the created object to access them. Again, using your code as an example you'd need to do:

Program myProgram = new Program(); // instantiate the object
myProgram.Addtion(ia, ja);

Simple solution is to put 'static' in front of the Addtion method

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.