Thursday, April 21, 2016

Events using EventHandler in C#

In today's post, I will be discussing Events using Event Handler in C#. This is in continuation with the previous week post here.

Events without using Delegates keyword explicitly

Last week we discussed what events are and how to use them in our application. We saw how to use events using delegates here. That post was more to show what's going on behind the scenes. The .NET framework has special guidelines on the delegates that can be used for events. The delegate type should have an object parameter and EventArgs parameter and should return void. So the .NET framework has defined a special delegate type called EventHandler for this purpose.

So the last week's example, if we were using EventHandler, will be as follows:


public class ListWithChangedEvent : ArrayList
{
    public event EventHandler Changed;
    protected virtual void OnChanged(EventArgs e)
    {
            if (Changed != null)
                Changed(this, e);
     }

    public override int Add(object value)
    {
        int i = base.Add(value);
         OnChanged(EventArgs.Empty);
        return i;
    }

    public override void Clear()
    {
        base.Clear();
        OnChanged(EventArgs.Empty);
    }

    public override object this[int index]
    {
        set
        {
            base[index] = value;
            OnChanged(EventArgs.Empty);
        }
    }
}

There is no delegate keyword being used explicitly and we just used EventHandler.

Internally, the EventHandler looks like as follows:

public delegate void EventHandler(object sender, EventArgs e);

So, to use the list we can do it the same way as previous post mentioned above:

static void Main(string[] args)
{
     ListWithChangedEvent list = new ListWithChangedEvent();
     list.Changed += ListChanged;
     list.Add("item 1");
     list.Clear();
     Console.ReadLine();
}

private static void ListChanged(object sender, EventArgs e)
{
     Console.WriteLine("This is called when the event fires without delegate.");
}

The list triggers event anytime the list items are changed.

Conclusion

So we saw a simple example of delegates usage using EventHandler. Using EventHandler helps us follow the .NET framework guidelines and adhere to the standard. It's good to know how the delegates work behind the scenes.

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)


Reference: MSDN

Thursday, April 14, 2016

Events Using Delegates in C#

In today's blog post, I will be discussing a simple example of events in C#. We will be using delegates in this post to explain how events work.

Events

An event is a way to notify clients of the occurrence of something of interest to the clients. Events follow a publish-subscribe model. Any client that wants to listen to an event can subscribe to it and when the event occurs the client is notified.

Events in C#

Events Using Delegates

I discussed delegates some time back here. Let's look at an example of how we can implement events using delegates. Here we have an ArrayList which invokes an event called Changed whenever the contents of the list change.

public delegate void ChangedEventHandler(object sender, EventArgs e);

public class ListWithChangedEvent : ArrayList
{
    public event ChangedEventHandler Changed;
    protected virtual void OnChanged(EventArgs e)
    {
            if (Changed != null)
                Changed(this, e);
     }

    public override int Add(object value)
    {
        int i = base.Add(value);
         OnChanged(EventArgs.Empty);
        return i;
    }

    public override void Clear()
    {
        base.Clear();
        OnChanged(EventArgs.Empty);
    }

    public override object this[int index]
    {
        set
        {
            base[index] = value;
            OnChanged(EventArgs.Empty);
        }
    }
}

The delegate is declared first which decides the method signature which can be assigned to the delegate. Next, we declare the special type of list.
Inside the ListWithChangedEvent, first the event is declared. Next, the event is invoked. Inside the method, we check if Changed is not null to avoid null exception. That's a standard practice to avoid null exception while invoking events. Other than that, standard methods are exposed to interact with the List and change it's contents. Inside each of the method, note that the OnChanged event is fired.

Suppose, we want to output a line whenever the event is fired. So we simply have a method like this:

private static void ListChanged(object sender, EventArgs e)
{
      Console.WriteLine("Event Occurred. List Changed.");
}

And then in the Main method we create the list, add the handler to the Changed event. Then, we call the Add and Clear method on the list.

static void Main(string[] args)
{
       ListWithChangedEvent list = new ListWithChangedEvent();
       list.Changed += new ChangedEventHandler(ListChanged);
       list.Add("item 1");
       list.Clear();
       Console.ReadLine();
}

As a result, the event is fired twice, once each for Add and Clear methods.
So we get the output like this:

Event Occurred. List Changed.
Event Occurred. List Changed.


Conclusion

So we saw how to use events using delegates in this post. Events help us decouple our code so the invoking code doesn't need to know what happens when the event is occurred. The calling code itself (or any other part of the system) can decide what to do when the event is fired.  Next week, I will be discussing how to use events without using delegates explicitly.

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)


Reference: MSDN

Thursday, April 7, 2016

Error & Exception Handling in C#

In today's blog post, I will be discussing error and exception handling in C#. We will also be discussing some new features of C# 6 for ways of exception handling.

Error & Exception Handling in C#

In order to make our application more resilient and robust, exception handling is inevitable. There could be several reasons for unforeseen errors in our application. Some times user might enter some bad data, some times some file may be missing, some times some server might be down, some times there might be division by zero and so on. If we don't have proper exception handling in place then our application might crash which certainly is not a nice user experience.

Try Catch Exception

If we have any potentially dangerous code which might throw exception, we can surround it by try block followed by a catch statement.
Here is a simple example:

try
{
       Console.WriteLine("Please Enter a number");
       var input = Console.ReadLine();
       var i = Convert.ToInt32(input);
       Console.WriteLine(String.Format("You entered number: {0}", i ));
}
catch (Exception e)
{
       Console.WriteLine("Number not valid.");
}
Console.ReadLine();

The code snippet asks user to input a number. If the number is valid then no exception is thrown. If the number is not valid, the code will throw an exception. Since we have a catch statement, we will get the output of number not being valid.

Here we had a generic exception handler which can handle any exception. If we want to have several exception handlers, each for several exception types, we can have those. We need to always have more specific exception type before less specific ones. These exception handlers are executed in order. As soon as the first match is found that catch block is executed.

Try Catch Finally

After the try block is executed, the catch exception block might be executed (if there was an exception), and then finally block is executed, if exists. The finally block is useful when we want to execute a block of code no matter if the exception occurred or not. This is useful if we open a file or database connection or something like that. We can close it as part of the finally block.

try
{
    //open connection
}
catch (Exception e)
{
    //handle exception
}
finally
{
    //close connection
}

Exception Filters

Suppose, we want to handle exception only if some specific condition satisfies. Otherwise, we don't want to handle the exception. Until C# 5, we had to do it this way:

try
{
      //Dangerous Code ;)
}
catch(Exception e)
{
     if(e.Message == "Message")
         //do something
     else
         throw;
}

So here we re-threw the exact same exception. The issue with this is that the stack trace is lost when we re-throw the exception. So we loose the information where the exception originally started.
In C# 6, we have exception filters which look like this:

try
{
      //Dangerous Code ;)
}
catch(Exception e) if(e.Message == "Message")
{
      //do something
}

This approach is much more cleaner and there is no re-throw of the exception, so no losing of stack trace.

Conclusion

Exception Handling is necessary for logging and better user experience. By examining these logs, we can improve the application performance too as exceptions generally slow down the application.

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)