Pages

13.6.12

Difference Between Events And Delegates in C#

It might be the syntax of C# that provides us with shortcuts to write delegates and events that causes this confusion.

In short, a delegate is a class that contains a field that holds a reference to a method and then you can call the method with appropriate parameters. Whereas an event is a variable that you can define and specify one or more delegates to be added to it.

Let's go through these examples to simplify and illustrate the idea.

class Program
{
  static void Main(string[] args)
  {
    DelegatesAndEvents obj = new DelegatesAndEvents();
    obj.Execute();
  }
}


public class DelegatesAndEvents
{
  public delegate void MyDelegate(int val);

  internal void Execute()
  {

    MyDelegate d = new
    MyDelegate(this.MyMethod);

    int val = 15;

    d.Invoke(val);
  }

  void MyMethod(int val)
  {
    Console.WriteLine(val);
    Console.ReadLine();
  }
}


In the previous code, I create a delegate type and name it MyDelegate. This delegate type is designed to call methods that take one parameter of type integer. What actually happens behind the scenes is that the CLR creates a class called MyDelegate and this class would have some fields and a method called Invoke. The invoke method takes one parameter of type integer.

In the execute method, I create an instance of the delegate (recall that a delegate is a class and I can create instances from it like any other class). The constructor of this MyDelegate takes one parameter of type integer. However, what I actually pass to the constructor is the name of the method I want to invoke and it will implicitly understand that I'm passing a reference to the method.

Another point that is worth mentioning is that I could have invoked the method without using the Invoke method. This is just a syntactical shortcut provided by C#. It would be like this:
d(val);


Now let's change our code a little bit. (comment added to show added, removed and changed code)
public class DelegatesAndEvents
{

  public delegate void MyDelegate(object sender, EventArgs e); // Changed

  internal void Execute()
  {

    MyDelegate d = new
    MyDelegate(this.MyMethod);

    EventArgs e = new EventArgs(); // Added
    object sender = 15; // Added

    d(sender, e); // Changed
  }

  void MyMethod(object sender, EventArgs e)
  {
    Console.WriteLine(sender);
    Console.ReadLine();
  }
}


What I did is just changing the parameters that MyDelegate is designed to take. Instead of taking one parameter of type integer, it now takes 2 parameters of types object and EventArgs, respectively. There's no big deal so far.

Now I will introduce an event and see how to use it. I will change the code a little bit. (comment added to show added, removed and changed code )

public class DelegatesAndEvents
{

  public delegate void MyDelegate(object sender, EventArgs e);
  public event MyDelegate MyEvent; // Added

  internal void Execute()
  {

    MyDelegate d = new MyDelegate(this.MyMethod);

    object sender = 15;
    EventArgs e = new EventArgs();

    MyEvent += new MyDelegate(d); // Added

    MyEvent(sender, e); // Added

    //d(sender, e);  Removed
  }


  void MyMethod(object sender, EventArgs e)
  {
    Console.WriteLine(sender);
    Console.ReadLine();
  }
}


Here's what I did in the last code change.I declared an event of type MyDelegate. In other words, I created an event that can hold delegates of type MyDelegate, so in the future I can use this event to invoke methods with the signature MyDelegate defines (methods that take 2 parameters of type object and EventArgs). And then,instead of invoking MyMethod directly using the delegate, I use the newly created event MyEvent to invoke the method.

As you can see, MyEvent is just a holder of delegates. I can add delegates to this event by using += syntax and passing the delegate instance in the constructor. I can add more than one delegate instance to this event. Look at the following code. (comment added to show added, removed and changed code )

public class DelegatesAndEvents
{

  public delegate void MyDelegate(object sender, EventArgs e);
  public event MyDelegate MyEvent;

  internal void Execute()
  {

    MyDelegate d = new MyDelegate(this.MyMethod);

    object sender = 15;
    EventArgs e = new EventArgs();

    MyDelegate d2 = new MyDelegate(this.MyMethod2); // Added

    MyEvent += new MyDelegate(d);
    MyEvent += new MyDelegate(d2); // Added

    MyEvent(sender, e);
  }

  void MyMethod(object sender, EventArgs e)
  {
    Console.WriteLine(sender);
    Console.ReadLine();
  }

  // This method is added
  void MyMethod2(object sender, EventArgs e)
  {
    Console.WriteLine(sender);
    Console.ReadLine();
  }
}

Instead of adding a delegate instance to the event the normal way, There's a syntax shortcut provided by C# that looks like this:
MyEvent += MyMethod;


So I can change my code to look like this: (comment added to show added, removed and changed code )

class DelegatesAndEvents
{

  public delegate void MyDelegate(object sender, EventArgs e);
  public event MyDelegate MyEvent;

  internal void Execute()
  {      

    //MyDelegate d = new MyDelegate(this.MyMethod);  Removed

    object sender = 15;
    EventArgs e = new EventArgs();

    //MyDelegate d2 = new MyDelegate(this.MyMethod2);  Removed

    MyEvent += MyMethod; // Changed
    MyEvent += MyMethod2; // Changed

    MyEvent(sender, e);
  }

  void MyMethod(object sender, EventArgs e)
  {
    Console.WriteLine(sender);
    Console.ReadLine();
  }


  void MyMethod2(object sender, EventArgs e)
  {
    Console.WriteLine(sender);
    Console.ReadLine();
  }
}


Notice that I no longer need to create delegate instances because the new syntax will implicitly create it.

Finally, let me introduce EventHandler, which is a delegate type itself. You can type EventHandler in your code in Visual Studio and press F12 to discover this.

namespace System
{

  [Serializable]
  [ComVisible(true)]
  public delegate void EventHandler(object sender, EventArgs e);

}


As you can see, EventHandler is a delegate type designed to invoke methods that take 2 parameters, object and EventArgs, exactly like MyDelegate that I defined in the previous code. Therefore, I can replace MyDelegate with EventHandlerand everything will be the same. The final code will be like this:

class DelegatesAndEvents
{    

  //public delegate void MyDelegate(object sender, EventArgs e);  Removed
  public event EventHandler MyEvent; // Changed

  internal void Execute()
  {
    object sender = 15;
    EventArgs e = new EventArgs();

    MyEvent += MyMethod;
    MyEvent += MyMethod;

    MyEvent(sender, e);
  }


  void MyMethod(object sender, EventArgs e)
  {
    Console.WriteLine(sender);
    Console.ReadLine();
  }


  void MyMethod2(object sender, EventArgs e)
  {
    Console.WriteLine(sender);
    Console.ReadLine();
  }
}


Normally, you don't go through all of the previous steps. You only see the last portion of code. All I was trying to do is to show you how this last code came.

now I hope it became clear that delegates are just types that you can create instances from. All delegates inherit from the classMulticastDelegate which is used to invoke other methods according to what we define. Events are meant to hold one or more delegate instance and once you raise the event, it invokes all the methods attached with those delegate instance.

8.6.12

Confusion when Passing Reference Type Objects in C#

Everybody knows that when making a method call in C#, reference type objects are passed by reference. In other words, whatever changes you make to your object in the called method will be reflected on the original one.

Let's examine the following code:

    class MyClass
    {
        public int MyInteger;
    }
    class Program
    {
        static void Main(string[] args)
        {
            MyClass myClass = new MyClass();
            myClass.MyInteger = 5;

            Console.Write("Value before method call: ");
            Console.WriteLine(myClass.MyInteger);
            MyMethod(myClass);
            Console.Write("Value after method call: ");
            Console.WriteLine(myClass.MyInteger);
        }            

        private static void MyMethod(MyClass myClass)
        {
            myClass.MyInteger = 10;
        }
    }
If you run the preceding code, it will show the following result:

Value before method call: 5
Value after method call: 10

This was expected. However, the idea that all reference type objects are passed by reference is not really accurate and the following proves so. If we change "MyMethod" by adding one line so it becomes as the following:
        private static void MyMethod(MyClass myClass)
        {
            myClass = new MyClass();
            myClass.MyInteger = 10;
        }

and then we run the program, guess what the result will be. The result will be as following:

Value before method call: 5
Value after method call: 5

The value of the field "MyInteger" did not change as you might expected. That is because what actually happens when you pass a reference type object to a method is that the reference to that object is copied and the copy is passed to the method. The new copy of the reference points to the same object, so if you make changes in the called method, you will be making changes on the same object. But if you create a new object in the called method, you will be actually changing the reference value that was passed and making it point to a new object. And whatever changes you make after this step will be irrelevant to the original object.

The following diagrams illustrates what happens in the previous 2 examples.

Example 1: What really happens when you pass an object
Example 1: What really happens when you pass an object

Example 2: Creating an instance inside the called method
Example 2: Creating an instance inside the called method



If you wish to make any changes to the object in the called method and have them all reflected on the original object even if you make a new instance in the called method, then what you need is to pass it by reference. You need to add the keyword ref before the object type in the method signature and also when calling the method. The code will look like this:

    class Program
    {
        static void Main(string[] args)
        {
            MyClass myClass = new MyClass();
            myClass.MyInteger = 5;

            Console.Write("Value before method call: ");
            Console.WriteLine(myClass.MyInteger);
            MyMethod(ref myClass);
            Console.Write("Value after method call: ");
            Console.WriteLine(myClass.MyInteger);
        }            

        private static void MyMethod(ref MyClass myClass)
        {
            myClass = new MyClass();
            myClass.MyInteger = 10;
        }
    }


Promotional Code for Udemy ServiceNow CIS - HR Practice Tests

If you're planning to become ServiceNow Certified Implementation Specialist - Human Resources (CIS-HR), you can prepare for the exam usi...