January 23, 2014

Exception Handling : The use of Try and Catch

New to C# ? Start from the beginning : Kick-Start C# : Your first program
Previous Post : Advanced CSharp Part 4 : Delegates and Events
Next Post : Threads in C# : Part 1

You are asked to write a program and then deliver it to your client. You have a nice looking User Interface and the next big thing that happened is that, your client provided a faulty input mistakenly and the program crashed! How often does that happen? Very often indeed. Exception handling can save you from such embarrassment and proved to be very developer friendly.

An Exception is basically an error that happens during your program's execution. But there is a fine line between an "error" and an "exception". When you forget to close a curly brace or put a using statement or a semicolon at the end, your compiler shows an error at compile time that "Hey you forgot or missed this and that!". Consider the case where you have a divide operation and the user mistakenly divides by zero! You cannot determine that at compile time, rather your program should be intelligent enough to determine that at run time! If such an operation is not dealt differently, your program is bound to crash.

So lets get familiar with the exception handling ecosystem.
  • The programmer anticipates that certain operation(s) is prone to errors.
  • Exceptions are raised, or thrown, when errors are encountered.
  • The anticipated portion of the program is written inside a try block.
  • When an error is encountered, the normal flow is interrupted and the control is given to the nearest exception handler- the catch block.
  • The .NET framework provides some exception handling classes. But you can build your own exceptions.
  • Three keywords are associated with exception handling - try, catch and finally.
Here is a working example.

using System;

namespace Spells
{
    class Program
    {
        public static void Main(string[] args)
        {
            int a=10, b=0, result=0;
            try
            {
                // piece of code that you anticipate can generate error
                result = a / b;
            }
            catch (Exception ex)
            {
                // deal with the exception
                // generally programmers show error message and wind up system resources inside this block
                Console.WriteLine("Exception handled. Message : {0}", ex.Message);
            }
            finally
            {
                // this block is always executed, with or without exceptions
                Console.WriteLine("Result {0}", result);
            }
            Console.Read();
        }
    }
}
The code is self-explanatory, necessary comments have been given in the snippet. If you type the code, a short-cut way to write try-catch is to write the word "try" and press "Tab" twice.
This is the output console.
The 1st line in the console window is line 19 in the code, while the 2nd console window line is line 24 in the code. Makes sense? The catch block optionally takes an argument of type Exception. Go to this MSDN link and scroll down to the bottom. You will find an Exception hierarchy where all the sub classes under Exception base class are mentioned. You can specify which type of exception you are trying to handle in the catch argument or you can specify the base class Exception type to catch all types of exceptions in a single catch block. If you remove all the try-catch-finally things and run the same code, your program will stop running in the middle, imagine that happening to a software product that you developed leaving no clue to the customer. The Message property is a useful property. I have used that property at line 19 to show what type of exception my program has encountered.

The basic essence that we get here is that, like other things in .NET, Exceptions are also objects. The .NET library has defined a whole lot of exception classes. Under these circumstances, you as a programmer need to be very specific about what type of exception you want to catch.
Consider the following two cases:
Case 1
Case 2

Can you explain what's the difference? The ArithmeticException is a superclass to DivideByZeroException class. So whatever errors that are related to Arithmetic operations, will be caught by this class, leaving the DivideByZeroException block unreachable. While writing catch block, you need to write hierarchically low descendents first. Since DivideByZeroException class is a subclass of ArithmeticException class, the Case 1 is appropriate while Case 2 generates a compile time error.

Custom Exception Class: You are eligible to write your own custom Exception classes. You will have to subclass the System.Exception and then build your own custom classes. Let's see a working example in action.

using System;

namespace Spells
{
    class UseOfSlangsException : Exception
    {
        public UseOfSlangsException()
            : base("Obscene word used")
        {
            this.HelpLink = "www.behave-well.net";
        }
    }
    class Program
    {
        public static void Main(string[] args)
        {
            string input;
            try
            {
                input = Console.ReadLine();
                if (string.Equals(input, "jackass", StringComparison.OrdinalIgnoreCase))
                {
                    throw new UseOfSlangsException();
                }
                else Console.WriteLine("Its clean!");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Hey! You have been warned. {0}\nHelp link {1}", ex.Message, ex.HelpLink);
            }
            finally
            {
                Console.WriteLine("Finally block");
            }
            Console.Read();
        }
    }
}
This is the output window.
 If you go to the MSDN link given above, you will see that the Exception class has some overloaded constructors, one of them taking a string message. This string message is passed through the Message property as seen on line 29. The custom exception class is on line 5, you are familiar with the notations of subclassing in C#. The constructor at line 7 takes no arguments, just passes a string to the base class constructor. The HelpLink is a property field. Observe line 23 where we create a new exception object of type UseOfSlangsException. This statement triggers the exception handling mechanism in the .NET framework and the code control is shifted to the catch block.

What have we learned so far? We have learned about the generic Exception class. We are also now able to build our custom exception handling classes. I really hope I have made these things clear to you. Happy Coding!

January 6, 2014

Avanced CSharp Part 4 : Delegates and Events

New to C# ? Start from the beginning : Kick-Start C# : Your first program
Previous Post : Advanced CSharp Part 3 : params, ref, out and Preprocessors
Next Post : Exception Handling : The use of Try and Catch

This post is fairly advanced and interesting. Both of the topics are interrelated. You cannot learn events unless you learn delegates. So I thought I should probably put the two in the same post to show how relevant they are.

Delegates: Delegates are essentially call-back methods. You are probably familiar with call-back functions if you happen to come from Java or Javascript background. Call-back function is something that can determine your flow of code at run time. You can switch in and out using a call-back function. Delegates provide this functionality in C#.

To use delegates in C#, you have to keep in mind three basic steps -
  1. Define a delegate.
  2. Assign a delegate variable to a method of same signature as 1.
  3. Implement the method with the same signature as 1.
The following is a delegate program in action.

using System;

namespace Spells
{
    public delegate void NameFactory(string name);  // step 1 define
    class Program
    {
        public static void Main(string[] args)
        {
            NameFactory Namer = FirstLast;      // step 2 assign
            string myname = Console.ReadLine();
            int indexofcomma = myname.IndexOf(',', 0);
            if (indexofcomma > 0)
            {
                // user input in the form of Last name, First name
                Namer = LastFirst;   // step 2 assign
                Namer(myname);
            }
            else
            { 
                // user input in the form of Firstname Lastname
                Namer(myname);
            }
            Console.Read();
        }
        static void FirstLast(string name)   // step 3 implement
        {
            Console.WriteLine("Firstname Lastname format: {0}", name);
        }
        static void LastFirst(string name)   // step 3 implement
        {
            Console.WriteLine("Lastname, Firstname format: {0}", name);
        }
    }
}
Essentially a delegate provides you a framework, it tells you how certain methods must be implemented.
Observe line 5 in the program. The delegate keyword is needed to define a delegate. It looks like a method, but essentially it tells the compiler how certain methods must look like. The void keyword says that the method following this delegate will not return anything at all. Choose a name for your delegate and then choose the argument types.

Now look at line 26 and 30. Both the methods have the same signature as we see on line 5. They take a string parameter and return nothing. Inside the Main function, we assign these methods to the delegate. Notice line 10 how we assigned FirstLast method to a variable Namer of type NameFactory. In the perspective of this code, this is just a default assignment. You will see that this program decides at run time which method to call. If there is a comma in the input string, we can assume that the given name is of the type Last name, First name. So we re-assign the delegate to LastFirst at line 16. If there is no comma in the input string, we call the previously assigned delegate as in line 22.

Line 17 and 22 can give you the impression that you are indeed calling the same method. This is exactly the beauty of delegate. As for line 17, Namer is pointing to LastFirst method, while line 22 points to the FirstLast method. This is how delegate helps you to change the callback method on the fly.

Events: Events are important part of programming software that does intelligent things. Events are something like that of an agent. You appoint an agent to look after "something", and when "something" happens, your agent reports to you that "hey you have been looking for something! Now something happened, do something with it."

Lets take a look at a working example and then I will explain what's going on.

using System;

namespace Spells
{
    public delegate void MyEventHandler(string theString);   // step 1

    class ListenChanges
    {
        private string str;
        public event MyEventHandler ValueChanged;       // step 2

        public string MyString
        {
            set
            {
                str = value;
                this.ValueChanged(str);     // step 3
            }
        }
    }
    class Program
    {
        public static void Main(string[] args)
        {
            ListenChanges changes = new ListenChanges();
            //step 4
            changes.ValueChanged += changes_ValueChanged;   // subscribing to event
            while (true)
            {
                string val = Console.ReadLine();
                if (string.Equals(val, "exit", StringComparison.OrdinalIgnoreCase))
                {
                    break;
                }
                changes.MyString = val;    // this will trigger the event
            }
            Console.Read();
        }

        static void changes_ValueChanged(string theString)
        {
            Console.WriteLine("Event raised: current value : {0}", theString);
        }
    }
}
There are 4 steps involved in using events. I have commented out 4 steps in the code. You need to define a delegate, precisely to say a frame of the method that you want to call when something happens. Line 5 does exactly the same and its step 1 for us.

The class from line 7-20 is just an example demonstration. Observe line 10 where I have used the keyword event. The event have been named as ValueChanged and note that this event is following the delegate that I defined on line 5. MyString is a property and I have used the setter field to set a new value. Whenever I set a new value, I want to raise an event and say "Hey something changed!". At line 17, I call the ValueChanged callback method. Erase line 17 and write the same thing again. Once you put a dot [.] after this, you will see a lightning bolt in the drop down suggestion list.
Lightning bolt indicates an event
Then in the Main function, I create an object of the class ListenChanges. Go ahead and erase line 27 as well as the method on line 40 and try writing again. As you write changes[dot]ValueChanged +=, you will see a prompt from your Visual Studio editor that asks you to press Tab.
Pres Tab prompt
The += symbol means that you are subscribing to an event, just like you subscribe to a blog or a Facebook profile. Oppositely, the -= would mean that you are unsubscribing from the event. If you press Tab, the Visual Studio editor will prompt you to press Tab yet again.
Press Tab prompt 2
You may choose not to press Tab, and instead you may provide your own implementation. This is just a visual support from the IDE and its really helpful. You will discover a method as in line 40 after you press Tab again.

I have created an infinite loop at line 28 and I will keep on taking input from the console until I type the word "exit". At line 35 I set the property value with the current input from the console. This is how my output console looks like.
Output Console
What just happened? You see, whenever you set the MyString property at line 35, the event gets fired and essentially the line at 42 is printed to the console. Isn't that amazing? This is how events actually help you listen to certain things or changes and makes your code dynamic. You will find regular use of events when you code on Windows Forms, WPF, Windows Store Apps or Windows Phone 8.

I hope I have made your life easier with delegates and events. If yes, all credits goes to you. If no, then the burden is on me! Happy Coding!

January 4, 2014

Advanced CSharp Part 3 : params, ref, out and Preprocessors

In this post we shall look into some advanced features of C# that were added in the recent versions of .NET framework. Some of these features are explicitly new for any programming language, and some of them you might have seen before in other languages.

Variable Parameter List: Sometimes it might happen that you are defining a method, but you are particularly not sure how many parameters you need. It means that the parameter list can vary while you are coding. In C#, the params keyword makes it possible. For example, the following method takes two integers as parameter and returns an integer.

int AddNums(int a, int b)
{
 int total = 0;
 total = a + b;
 return total;
}
The problem with this snippet is that, you are stuck with two arguments only. May be you could define overloaded methods with increasing number of arguments. But what if someone wants to add 8 integers? Surely you would not want to construct a method that has 8 different arguments! C# brings to you an elegant solution.

int result = AddNums(4,7,25,36,8);
int result2=AddNums(7,9);  
int AddNums(params int[] n)
{
 int total = 0;
 foreach(int i in n)
 {
  total += i;
 }
 return total;
}
Instead of taking a particular number of arguments, I tell my compiler that you can expect one or more than one arguments, in that case you should store them in the array. Then inside the body of the method, you loop over the array and do what you need to do.
A matter of caution for everyone. You cannot do something like the following:

int AddNums(params int[] n,int g,string str,object ob)
{
 int total = 0;
 foreach(int i in n)
 {
  total += i;
 }
 return total;
}
When you declare a method like that, you will get compiler error saying that params should be the last argument in a method. What it really means is that if you put more arguments after params, it really gets confused as to how many arguments it should put inside the array. However the following snippet is perfectly okay!

int AddNums(int g,string str,object ob,params int[] n)
{
 int total = 0;
 foreach(int i in n)
 {
  total += i;
 }
 return total;
}
Method Parameter Modifiers: Apart from passing variable number of arguments, you can in fact play with the way arguments behave and method return type in C#. We shall look into certain keywords like ref and out.
If you are familiar with other languages, you probably know that in most cases, passing parameters to functions or methods are usually done by value. Pass by value is desirable in most cases, but it can cause you some difficulties if you as a programmer aren't careful about what you want to achieve from your code. Look at the following code and run the code.

using System;

namespace Spells
{
    class Program
    {
        public static void Main(string[] args)
        {
            int j = 15;
            Console.WriteLine("Inside Main j={0}", j);
            MyMethod(j);
            Console.WriteLine("Inside Main j={0}", j);
            Console.Read();
        }
        static void MyMethod(int x)
        {
            x += 100;
            Console.WriteLine("Inside MyMethod x={0}", x);
        }
    }
}
The value of j does not change even after you call the method and add 100 to it. If you want to keep the changed value from the calling routine, you can add the ref keyword. In that way, you pass the parameter as reference, not by value.

using System;

namespace Spells
{
    class Program
    {
        public static void Main(string[] args)
        {
            int j = 15;
            Console.WriteLine("Inside Main j={0}", j);
            MyMethod(ref j);
            Console.WriteLine("Inside Main j={0}", j);
            Console.Read();
        }
        static void MyMethod(ref int x)
        {
            x += 100;
            Console.WriteLine("Inside MyMethod x={0}", x);
        }
    }
}
Add the keyword ref at line 11 and 15. You are ready to see a persisting change in the value of j after calling the method.

There is an out keyword that is most useful when you want multiple return values from the method via the parameters. Lets see a working example.

using System;

namespace Spells
{
    class Program
    {
        public static void Main(string[] args)
        {
            int j = 15;
            double square, cube;
            MyMethod(j, out square, out cube);
            Console.WriteLine("Square of j={0} is {1} and cube is {2}", j, square, cube);
            Console.Read();
        }
        static void MyMethod(int x, out double sqr, out double cube)
        {
            sqr = x * x;
            cube = x * x * x;
        }
    }
}
Observe that the variables square and cube have been assigned the return values from the function. This is a real nice way to assign values to a parameter that you are passing from the calling routine.

Preprocessor: Essentially it means to pre process something before the compilation of the code. Preprocessor directives give directions to the compiler. A preprocessor starts with a # , you may call it hash symbol or the pound symbol. There are a handful of preprocessors like #define, #undef, #if, #else, #elif, #endif, #region, #endregion etc. Let us see a working example.

#define SPELLS
#define HELLO
using System;

namespace Spells
{
    class Program
    {
        public static void Main(string[] args)
        {
#if SPELLS
            Console.WriteLine("SPELLS has been defined");
#else
            Console.WriteLine("SPELLS not defined");
#endif
#if HELLO
            Console.WriteLine("I say Hello");
#else
            Console.WriteLine("No Hello");
#endif
            Console.Read();
        }
    }
}
The #define must be placed above any other piece of code in the file. Go ahead and place at any other place, you will get a red squiggle representing error. So what exactly this piece of code is doing? Go ahead and paste this code in your CSharp editor.  You will see that line 14 and 19 is grey. This signifies that these lines are not part of current execution. Why? Because you see, at line 1 and 2, I have defined two symbols, namely SPELLS and HELLO. The compiler treats them as a single symbol. At line 11 and 16, I check if these symbols have been defined or not. This is just like the if-else that we used to write normally. When the compiler finds the required symbol, it allows the execution of code under that symbol.

Go ahead and change the symbols to anything you like at line 1 and 2 or simply remove them completely. You will notice that line 14 and 19 have been activated, while line 12 and 17 are currently grey-ed. This perplexing features comes handy when you are debugging your code. When you are trying to ship your debugged code to another person, you may want to run the debugging regions. Again, when you are done with debugging, you may choose to run the to-be-official code.

There is a one final important thing that you should see. Copy and paste the following code in your C# editor.

using System;

namespace Spells
{
    class Program
    {
        public static void Main(string[] args)
        {
            Method1();
            Method2(4, "Hi");
            Console.Read();
        }
        #region This is Method1
        static void Method1()
        { 
            // code here
        }
        #endregion

        #region This is Method2
        static void Method2(int a, string str)
        { 
            // code here  
        }
        #endregion
    }
}
The #region and #endregion does not affect the flow of your code, it simple enhances the beauty of your editor. I have two regions around two methods. Look at line 13 and 20, the string following #region is simply a name that you prefer to name the region. Now what's so interesting about this? Go ahead and click on the small box [-] beside line 13 and 20.
Visual Studio Editor Environment

Aha! Your editor squeezed the code there and you just have a clean editor. This is how it looked in my case.
Visual Studio Editor Environment
[-] interprets to minimizing the code or collapsing the code, while [+] interprets to expanding or maximizing the code region. This feature is particularly helpful when you have a large, very large piece of code.

I hope these little features come handy to you. I also hope you have found this post helpful. In the next post we shall learn about delegates and events.