Why does calling a simple method in a class give a reference error?

3

I'm starting to study C # and I get the following error:

  

CODE: CS0120
DESCRIPTION: An object reference is required for   the non-static field, method, or property   'Program.SomarNumeroes (int, int)'
CODE: CS0120
DESCRIPTION:   An object reference is required for the non-static field, method, or   property 'Program.dizOla ()'

namespace metodo_e_funcao
{
    class Program
    {
        public int SomarNumeros(int a, int b)
        {
            int resultado = a + b;
            if (resultado > 10)
            {
                return resultado;
            }
            return 0;
        }

        public void dizOla()
        {
            Console.WriteLine("Ola");
        }

        static void Main(string[] args)
        {
            int resultado = SomarNumeros(10,11);
            Console.WriteLine(resultado);
            dizOla();
        }
    }
}
    
asked by anonymous 24.08.2016 / 21:16

1 answer

4

It seems to access methods directly without instantiating an object, so the method must be static.

Of course, static methods can not directly access instance members. The fact that Main() is static would already prevent instance members from accessing this class if it was done.

using System;

namespace metodo_e_funcao {
    public class Program {
        public static int SomarNumeros(int a, int b) {
            int resultado = a + b;
            if (resultado > 10) {
                return resultado;
            }
            return 0;
        }

        public static void dizOla() {
            Console.WriteLine("Ola");
        }

        public static void Main(string[] args) {
            int resultado = SomarNumeros(10, 11);
            Console.WriteLine(resultado);
            dizOla();
        }
    }
}

See working on dotNetFiddle in a simplified way.

Read more about the subject .

    
24.08.2016 / 21:20