-1

Guys i need some help here, i have error in Line 50: CS0236 C# A field initializer cannot reference the non-static field, method, or property Line 51: CS0236 C# A field initializer cannot reference the non-static field, method, or property

namespace ConsoleApplication5
{
    public delegate string Metodo(string t1, string t2);

    class Program
    {
        static void Main(string[] args)
        {

        }
    }

    public class ExemploDel
    {
        public static string NomeMetodo(string t1, string t2)
        {
            return t1 + t2;
        }

        Metodo meuMetodo = NomeMetodo;
    }

    public class Metodos
    {

        public string Method1(string tx1, string tx2)
        {
            return tx1 + tx2;
        }
        public string Method2(string tx1, string tx2)
        {
            return tx2 + tx1;
        }
    }

    public class DelegatesEx
    {
        public static string NomeMetodo(string t1, string t2)
        {
            return t1 + t2;
        }

        Metodos obj = new Metodos();
        Metodo m1 = obj.Method1;
        Metodo m2 = obj.Method2;
        Metodo m3 = NomeMetodo;

    }
}
kydros
  • 13
  • 6
  • Did you read the error message? It's pretty clear. If you still don't get it, have you tried Googling it? This error is extremely common. To give you some general pointers: Your code in DelegatesEx after `NomeMetodo` isn't inside a method. You're also referencing methods like they're properties. – tnw Apr 04 '17 at 15:33

1 Answers1

0

First of all, you have placed the calling code at wrong place, the following 4 lines should go in the Main method of your program:

Solution1:

class Program
{
    static void Main(string[] args)
    {
       Metodos obj = new Metodos();
       Metodo m1 = obj.Method1;
       Metodo m2 = obj.Method2;
       Metodo m3 = NomeMetodo;
    }
}

Secondly, you have marked your delegate as static while you are trying to assign it instance method, so either make the delegate non-static in declaration and make the methods static.

public delegate string Metodo(string t1, string t2);

Solution2:

if you want to keep the Metodo delegate static, then your methods should also be satic like:

public class Metodos
{

        public static string Method1(string tx1, string tx2)
        {
            return tx1 + tx2;
        }
        public static string Method2(string tx1, string tx2)
        {
            return tx2 + tx1;
        }
}

and now your main method code will also be changed, as static methods are access using the class not instance of it:

class Program
{
    static void Main(string[] args)
    {
       Metodo m1 = Metodos .Method1;
       Metodo m2 = Metodos .Method2;
       Metodo m3 = NomeMetodo;
    }
}
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160