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

Asked

Viewed 3,125 times

3

I’m starting to study C# and I’m making the following mistake:

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();
        }
    }
}

1 answer

4


It seems to access the methods directly without instantiating an object it is necessary that the method is static.

Obviously static methods also cannot directly access instance members. The fact of Main() being static would already prevent access of instance members of that class if it were 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();
        }
    }
}

Behold working in the ideone more simply. And in the .NET Fiddle. Also put on the Github for future reference.

Read more on the subject.

  • Got it understood, Thanks :D worked, from here 6 min I accept the answer

Browser other questions tagged

You are not signed in. Login or sign up in order to post.