Monday 1 February 2016

What is event in c# ? How to create it ?



An event in C# is a way for a class to provide notifications to clients of that class when some interesting thing happens to an object. The most familiar use for events is in graphical user interfaces; typically, the classes that represent controls in the interface have events that are notified when the user does something to the control (for example, click a button).
Events, however, need not be used only for graphical interfaces. Events provide a generally useful way for objects to signal state changes that may be useful to clients of that object. Events are an important building block for creating classes that can be reused in a large number of different programs.
Events are declared using delegates. If you have not yet studied the Delegates Tutorial, you should do so before continuing. Recall that a delegate object encapsulates a method so that it can be called anonymously. An event is a way for a class to allow clients to give it delegates to methods that should be called when the event occurs. When the event occurs, the delegate(s) given to it by its clients are invoked.

Example:-



using System;

    class MyClass
    {
        public delegate void MyDelegate(string message);
        public event MyDelegate MyEvent;

        //this method will be used to raise the event.
        public void RaiseEvent(string message)
        {
            if (MyEvent != null)
                MyEvent(message);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            MyClass myClass1 = new MyClass();
            myClass1.MyEvent += new MyClass.MyDelegate(myClass1_MyEvent);

            Console.WriteLine("Please enter number\n");
            string msg = Console.ReadLine();

            //here is we raise the event.
            myClass1.RaiseEvent(msg);
            Console.Read();
        }
        //this method will be executed when the event raised.
        static void myClass1_MyEvent(string message)
        {
            Console.WriteLine("Your Message is: {0}", message);
        }
    }




Output:-













What is Delegates in C# Example ? Use of Delegates in C#



Basically delegates in c# are type safe objects which are used to hold reference of one or more methods in c#.net. Delegates concept will match with pointer concept of c language. 

Whenever we want to create delegate methods we need to declare with delegate keyword and delegate methods signature should match exactly with the methods which we are going to hold like same return types and same parameters otherwise delegate functionality won’t work if signature not match with methods.

Example:-

using System;

namespace ConsoleDemoApp
{
    public delegate int DelegatSample(int a, int b);
    public class Sampleclass
    {
        public int Add(int a, int b)
        {
            return a + b;
        }
        public int Sub(int a, int b)
        {
            return a -b;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Sampleclass sc = new Sampleclass();

            DelegatSample delgate1 = sc.Add;
            int i = delgate1(100, 200);
            Console.WriteLine(i);
            DelegatSample delgate2 = sc.Sub;
            int j = delgate2(200, 100);
            Console.WriteLine(j);
            Console.ReadKey();
        }
    }

}



Output:-



















What is the use of Delegates?

Suppose if you have multiple methods with same signature (return type & number of parameters) and want to call all the methods with single object then we can go for delegates.

Delegates are two types

      -  Single Cast Delegates
      -  Multi Cast Delegates

Single Cast Delegates

Single cast delegate means which hold address of single method like as explained in above example.

Multicast Delegates

Multi cast delegate is used to hold address of multiple methods in single delegate. To hold multiple addresses with delegate we will use overloaded += operator and if you want remove addresses from delegate we need to use overloaded operator -=

Multicast delegates will work only for the methods which have return type only void. If we want to create a multicast delegate with return type we will get the return type of last method in the invocation list




Check below sample code for multicast delegate declaration and methods declaration


public delegate void MultiDelegate(int a,int b);
public class Sampleclass
{
public static void Add(int x, int y)
{
Console.WriteLine("Addition Value: "+(x + y));
}
public static void Sub(int x, int y)
{
Console.WriteLine("Subtraction Value: " + (x - y));
}
public static void Mul(int x, int y)
{
Console.WriteLine("Multiply Value: " + (x * y));
}
}
class Program
{
static void Main(string[] args)
{
Sampleclass sc=new Sampleclass();
MultiDelegate del = Sampleclass.Add;
del += Sampleclass.Sub;
del += Sampleclass.Mul;
del(10, 5);
Console.ReadLine();
}
}


Output:-