Delegate program

I made a very simple delegate program. I have no idea why this shows an error, although I compared it to the one that was listed in the MSDN library, the same one as in MSDN still does not compile ... the error says: "Add name does not exist in current context, "as well as for another method. Subtract. Please help me find what the problem is.

namespace DelegatePrac
{   
   public delegate void One(int a, int b); 
    public class Some
     {
  static void Add(int a, int b)
       { 
      int c = a + b;    Console.WriteLine("{0}",c);
       }
       static void Subtract(int a, int b)
       { int c = a - b;  Console.WriteLine("{0}",c);
       }

    }

    class Program
    {
        static void Main(string[] args)
        {
            One o1,o2;
            o1 = Add;//gives error here
            o2 = Subtract;//and here!!
            o1(33,44);
            o2(45, 15);
         Console.ReadLine();
        }
    }
}

I followed this link - http://msdn.microsoft.com/en-us/library/ms173175.aspx

thank

+3
source share
3 answers

You should see a compiler message:

The name "Add" does not exist in the current context.

, , Add ; Add Some - :

o1 = Some.Add;
o2 = Some.Subtract;

; ( ) , , .

:

'DelegatePrac.Some.Add(int, int)' -

, ; public ( internal) :

public static void Add(int a, int b) {...}
+8

?

o1 = Some.Add;
o2 = Some.Subtract;

, Add Subtract, , , , Add Subtract .

ssd , public . - , private.

+2

Two things:

  • You need to be noted Addand the Subtractlike public.
  • They are not part class Program. Therefore, using them in classes other than Some, you need to indicate that they are part Some, using Some.Addand Some.Subtract.

Corrected Code:

namespace DelegatePrac
{   
    public delegate void One(int a, int b); 

    public class Some
    {
        public static void Add(int a, int b)
        { 
            int c = a + b;    Console.WriteLine("{0}",c);
        }

        public static void Subtract(int a, int b)
        { 
            int c = a - b;  Console.WriteLine("{0}",c);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            One o1,o2;
            o1 = Some.Add;//gives error here
            o2 = Some.Subtract;//and here!!
            o1(33,44);
            o2(45, 15);
            Console.ReadLine();
        }
    }
}
+2
source

Source: https://habr.com/ru/post/1784950/


All Articles