Tuesday, December 6, 2011

Event

Event:
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.

Example:

    class Program
    {
        static void Main(string[] args)
        {
            var dialogForm = new DialogForm();
            dialogForm.OnDialogClosed += new DialogForm.DialogClosed(dialogForm_OnDialogClosed);

            Console.WriteLine("Dialog is shown.");
            dialogForm.ShowDialog();
            
            Console.WriteLine("Dialog data is saved.");
            dialogForm.SaveData();

            Console.ReadLine();
        }

        static void dialogForm_OnDialogClosed(object sender)
        {
            //Take action after closed dialog
            Console.WriteLine("Dialog is closed.");
        }
    }

    class DialogForm
    {
        public delegate void DialogClosed(object sender);
        public event DialogClosed OnDialogClosed;
        
        public void ShowDialog()
        {
            
        }
        public void SaveData()
        {
            if (OnDialogClosed != null)
                OnDialogClosed(this);
        }
    }

Explanation:
Here DialogClosed is a delegate and OnDialogClosed is an event.
Scenario : We want to show a dialog form where user can enter some data and after that he can save data. When data has been saved then a closed event fire from Dialog to notify caller that I have closed.

Sunday, December 4, 2011

Anonymous Method

Anonymous Method :
We have seen a delegate now it's time to know about Anonymous Method. So we can create a delegate instance without using method name.

Example :
    class Program
    {
        public delegate int OperationDelegate(int a, int b);
        static void Main(string[] args)
        {
            OperationDelegate addOperation = delegate(int a, int b)
            {
                return a + b;
            };
            Console.WriteLine(addOperation(10, 20));
            Console.Read();
        }
    }

Explanation:
We have put a method inside a block. which is anonymous method.