Nate
Nate

Reputation: 919

Passing Delegates to Events c#

Reading event description and examples of msdn I can see a discrepancy in the way events are subscribed to. Sometimes event handlers are passed "as is" and other times they are passed by instantiating a delegate using the handler method e.g.

...
class Subscriber
    {
        private string id;
        public Subscriber(string ID, Publisher pub)
        {
            id = ID;
            // Subscribe to the event using C# 2.0 syntax
            pub.RaiseCustomEvent += HandleCustomEvent;
        }

        // Define what actions to take when the event is raised. 
        void HandleCustomEvent(object sender, CustomEventArgs e)
        {
            Console.WriteLine(id + " received this message: {0}", e.Message);
        }
    } 

vs

public delegate void EventHandler1(int i);
...
public class TestClass
{
    public static void Delegate1Method(int i)
    {
        System.Console.WriteLine(i);
    }

    public static void Delegate2Method(string s)
    {
        System.Console.WriteLine(s);
    }
    static void Main()
    {
        PropertyEventsSample p = new PropertyEventsSample();

        p.Event1 += new EventHandler1(TestClass.Delegate1Method);
        p.RaiseEvent1(2);
       ...
     }
}

Can someone please provide clarity on this?

Thanks.

Upvotes: 1

Views: 175

Answers (1)

SLaks
SLaks

Reputation: 888107

Your first code sample is syntactic sugar for the second one.
This syntax (omitting the constructor) was introduced by C# 2.

Upvotes: 5

Related Questions