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

59 views Asked by At

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");
    }
  } 
}
1

There are 1 answers

0
trix On BEST ANSWER

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