Search code examples
c#visual-studiodelegatesmulticastdelegate

Code is compiled and run successfully but expected output is to print "Sub" is not getting printed. What is the error in this code?


What is the problem in this code?

namespace ConsoleApplication1
{
public delegate void del();

class Program
{
    static void Main(string[] args)
    {
        del d = new del(add);
        d += sub;
    }

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

    public static void sub()
    {
        Console.WriteLine("Sub");
    }
  } 
}

Solution

  • You need to invoke your delegate:

    class Program
    {
        static void Main(string[] args)
        {
            del d = new del(add);
            d += sub;
    
            d.Invoke();
        }
    
        public static void add()
        {
            Console.WriteLine("add");
        }
    
        public static void sub()
        {
            Console.WriteLine("Sub");
        }
      } 
    }