0

Can anyone say the difference between static/object method call vs delegate method call here the sample provided from my end.

class Program
{
    private delegate void TestDeleg1(string input1);
    static void Main(string[] args)
    {
        // Using delege & Lambda expression
        TestDeleg1 testDeleg1 = input => { var test = "Hai " + input; Console.WriteLine(test); };
        testDeleg1("Microsoft");

        // Using simple static method invoke
        TestImplementation("Microsoft");
        Console.ReadLine();
    }

    public static void TestImplementation(string input1)
    {
        var test = "Hai " + input1;
        Console.WriteLine(test);
    }
}

Because I didn't find any real time usage of delegate method call.

Thanks, S.Venkatesh

0

2 Answers 2

5

In your example.. there's no difference in their usage. Architecturally however, they are quite different. A delegate is a reference to a method. A static method is.. a method.

Delegates can change what method they reference.. however, a method is just that.. a method.

1
  • 1
    If you find time share the difference with real usage Aug 7, 2012 at 7:02
1

The usefulness of delegates also comes from the fact that they are types that can be used for example as parameters to methods. For example if you declare

internal delegate bool PredicateOnInt32(int x);

then PredicateOnInt32 is a kind of reference type, and you can use it as a parameter in a method, like

internal int GetFirstNumberWhere(PredicateOnInt32 pred)
{
  foreach (int num in this.numbers)
  {
    if (pred(num))
      return num;
  }
  throw new InvalidOperationException("No number satisfies the specified prediacte");
}

This is just an exemple, of course. But think of LINQ and you understand that it can be useful to have a type that represents a method (or several methods) of a specific signature and return type.

Another use of delegates is in events where a delegate instance is used behind the scene to hold the collection of methods to be invoked when the event "happens". For example when a button is clicked. Different "subscribers" can then add their own methods to the delegate, through the add accessor of the event.

Not the answer you're looking for? Browse other questions tagged or ask your own question.