October 2, 2016

Installing scikit-learn in Windows : The Easy Way

I recently found myself in need of a quick prototyping tool for machine learning. That was when a dear friend of mine suggested to try out scikit-learn. I didn't know Python. Yet, however, that wasn't what disappointed me. You know you can learn Python in a day or two. Thats not the point. Your patience will be called in to action when you start setting up environment for development in Windows, or lets just say there's no easy getaway with installing anything on Windows.

I am using Windows 7 here. For those of you who are trying to get on with scikit-learn in your Windows machine, start with Python 2.7. I am assuming that you have your environment ready with Python and pip. If you are not, then set your environment PATH variable with C:\Python27\Scripts. This will allow your machine to recognize pip.

If you look at how to install scikit-learn page, there are two dependencies -
  • NumPy, and
  • SciPy
Before you install scikit-learn, you are required to have NumPy and SciPy in your machine. Now a lot of people stumbled upon this part because of a number of known reasons. A bit of googling will lead you to some stackoverflow posts. I will summarize here some known issues -
  1. Missing Visual C++ for Python 2.7. Just download and install VC compiler for Python 2.7. That will solve this issue.
  2. SciPy not installed [not properly installed!]
  3. Numpy+MKL is missing
There are other issues, but I think someway or the other, these three are related and core to installation problems. You can avoid the trouble by following this way -
  1. Download NumPy binary from here. DO NOT pip install numpy. Go to the directory where this file has been downloaded, open command prompt, write pip install "numpy-1.11.2rc1+mkl-cp27-cp27m-win32.whl".
  2. Download SciPy binary from the same site. Follow the same procedure above and write pip install scipy-0.18.1-cp27-cp27m-win32.whl.
  3. Finally if numpy and scipy installations are successful, install scikit-learn by writing pip install -U scikit-learn.
At this point, scikit-learn should work in your Windows 7 machine. 

June 26, 2014

Threads in C# : Part 1

New to C# ? Start from the beginning : Kick-Start C# : Your first program
Previous Post : Exception Handling : The use of Try and Catch

Well this is my first post in 5 months! And this is one piece of a topic to start writing again.

Understanding threads in C# require a bit of concepts from Delegates. You can brush up your delegate knowledge in my earlier post: Delegates and Events.

If you are a programmer and there's one single topic that bites you every time you encounter it, its Thread. Threads can be termed as lightweight Processes. If you are yet to take an Operating System course in your undergrad, you are probably not familiar with "Process". But don't worry, we don't need this concept here.

Let us try to understand why threads are necessary. Consider the case where you have developed a downloader software. Your software is the next big thing that people talk about! Y is a user and he is trying to download a 1 GB movie. Remember that your software is really good! So what does a good software do? It shows its user whats happening inside, intuitively, has a nice User Interface, right? Let us think simple from this point. Your machine is downloading data from a remote server, so your CPU must be busy processing that task, right? If your CPU is busy with that, then how do you show an intuitive progress bar? More importantly, if your user doesn't want to download it anymore, he should be able to cancel the operation with a Stop or Pause button. If the CPU is busy with grabbing data, your GUI will not interact with the user.

Threads make sure that critical parts of your program stay alive and interactive. Typically, threads are implemented when programs are CPU and memory intensive. Often threads are used to improve the response time of the software.

So lets get started with threads. The simplest way to create a thread is to create a new instance of the Thread class. The .NET framework provides us with the System.Threading namespace for creating and managing threads. The Thread constructor takes a single argument: a delegate type. The Common Language Runtime (CLR) provides a delegate class called ThreadStart. It points to the method that we want to run when the thread starts. Its more like "hey when you start, run this method".

public delegate void ThreadStart();
The delegate looks like the above. As you know from your knowledge on delegates, the methods that this delegate would point to should have the same signature as the delegate.

Here is a complete code using Threads in C#.

It may look a bit long and unnecessarily huge. But its always best to learn in simple manners.

Line 19 and 20 are the ones that we have been talking about. t1 is an object of type Thread. The Thread constructor takes as argument a ThreadStart type delegate. In this case, ThreadStart delegate points to the Increment method. Take a good note at the signature of Increment method. The method signature tells us that this method takes nothing as argument and returns nothing to the caller.

Finally, we need to tell the compiler when to start scheduling them. Line 22 and 23 does that for each of the thread objects. You can put t2 before t1. Basically it is up to the programmer which one to put first, but honestly it matters less.
Run 1

Run 2

I have put two screenshots of the program running on my machine. If you run it yourself, you may see a similar one, slightly different, or entirely the same.

Threads are more or less difficult to grab. They are also difficult to picture in the brain. The two screenshots merely points out that we cannot correctly anticipate the order of how two or more threads are running and switching. At least, it points out an idea; for example, if one thread is a grabbing data from the server and another is updating the UI, we will see an interactive thing going on in our screen. We know computers operate very fast. Our CPU lets each of the thread run for a while, and we get the illusion of a super interactive software on our screen.

Thanks for reading!

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.

December 31, 2013

Advanced CSharp Part 2 : Structs and Interfaces

We shall continue on more advanced features on CSharp. We have already seen how to use classes on different circumstances and how to modify its behavior under certain restraints; in this post we shall see two more data types that provide "class" type facilities, yet very different in nature and usages.

Struct: We start with structs. If you are familiar with C or C++, you are already acquainted with structs. Structs are similar to classes, but comes with some important differences.
  • Classes are reference types, while structs are value types.
  • They do not support inheritance. They do not derive (subclass) other struct types.
  • It is not possible to initiate a variable inside the struct definition. You have to do the initialization outside.
 The essential theme of using either of the class or a struct is the same: you want to keep logically relevant data together. So how do we understand when to use class or struct? We use struct when we have a small and simple data to handle. You just really don't need to mess up with classes when you need to handle just two or three variables and member fields. structs also allow properties and constructors like classes do. Let's see a working example.

using System;

namespace Spells
{
    public struct MyPoint
    {
        int x;
        int y;
        public MyPoint(int _x, int _y)
        {
            x = _x;
            y = _y;
        }
        public int Xcord 
        { 
            get { return x; }
            set { x = value; }
        }
        public int Ycord 
        {
            get { return y; }
            set { y = value; }
        }
    }
    class Program
    {
        public static void Main(string[] args)
        {
            MyPoint point = new MyPoint(4, -7);
            Console.WriteLine("point X = {0}, Y = {1}", point.Xcord, point.Ycord);

            MyPoint npoint = new MyPoint();
            npoint.Xcord = 64;
            npoint.Ycord = 45;
            Console.WriteLine("npoint X = {0}, Y = {1}", npoint.Xcord, npoint.Ycord);

            Console.Read();
        }
    }
}
Line 5 is no different than what you used to do while using classes. The only thing different is the keyword struct instead of class. I have used two variables of int types to indicate the x and y coordinates. Line 9 is a constructor that takes two arguments. Line 14 and 19 are two properties with getter and setter fields. I have created two instances of this struct inside the Main method. Consider line 29 and 32. You will see two different ways of instantiating struct type variables. Note that I have provided only a constructor that takes two arguments (see line 9). But still I am able to instantiate npoint at line 32 that takes no arguments. You can't really do that with classes.

You could still use a class instead of struct. But you use a struct when you see that you have lesser data to handle and you do not need additional methods to handle logic inside your program.

Interface: An interface is essentially a class. It's a close cousin of abstract class. Interfaces provide a way of grouping a set of common behaviors in a single place. They provide a specification rather than an implementation. If you are not familiar with abstract classes, you can get an idea in the last post. Consider the building codes class that we used earlier. If it happens that there are certain more regulations that builders must follow, then it will create a problem in your program because you cannot inherit more than one abstract class. But classes can in fact inherit multiple interfaces. Interfaces are more like behaviors. You implement these behaviors to the classes whoever wish to implement your interface.

using System;

namespace Spells
{
    interface IUtilities /* it is a convention to start interface name with 'I' */
    {
        bool Gas();         /* no method implementation logic here */
        bool Water();
        bool Electricity();
    }
    interface ICommercial
    {
        void Commercial();
    }
    interface IHousehold
    {
        bool Housing();
    }
    public class Hotel : IUtilities, ICommercial  /* multiple interfaces */
    {
        public bool Gas()
        { //codes here
            return true;
        }
        public bool Water()
        { //codes here
            return true;
        }
        public bool Electricity()
        { //codes here
            return true;
        }
        public void Commercial() { /*codes*/ }
        // other methods and members
    }
    public class MyHome : IUtilities, IHousehold
    {
        public bool Gas()
        { //codes here
            return true;
        }
        public bool Water()
        { //codes here
            return true;
        }
        public bool Electricity()
        { //codes here
            return true;
        }
        public bool Housing()
        {
            return true;
        }
    }
    class Program
    {
        public static void Main(string[] args)
        {
            
            Console.Read();
        }
    }
}
Build this code (F6). You will get a successful build. Line 5, 11 and 15 shows interface definition. It is a convention to name an interface with an uppercase 'I'. You may choose not to do so. Inside the interfaces definition, observe that there is no logic implementation here. You just specify which methods the implementing classes must implement. 

Line 19 and 36 shows how to implement interfaces in a class. The most important point is that you are able to implement multiple interfaces separated by comma. Also observe that you have to use the keyword public in front of the implementing methods. Go ahead and erase one of the methods from Hotel class. Your code will fail to build with an error.

To sum up, interfaces are nice way to force you to implement certain functionalities inside your code. An alternative is abstract class. But if you have multiple classes to inherit, you better make them interfaces and implement them as you can see above. 

December 26, 2013

Advanced CSharp Part 1 : Overriding Methods, Abstract and Sealed Classes

We shall take a step further on our CSharp journey. We shall take a look at some of the complex object oriented programming practices. We have already learnt how to declare classes and methods, we also know about method overloading. In this post, we shall take a look at somewhat a close cousin called method overriding. In addition we shall take a look at abstract and sealed classes. These concepts are seldom used in small projects like console applications, but influences heavily in large projects or developing third party libraries.

Overriding Methods: Overriding is the ability to control method behavior in object oriented programming. If you are familiar with OOP based languages like Java, you already know how they work. Lets look into a practical example.

Inheritance and Methods
Any region bounded by four sides is a quadrilateral. Three very common variants of a quadrilateral are rectangle, square and a parallelogram. We can safely assume that these three variants inherit some basic properties from the very basic and common: the Quadrilateral. So Quadrilateral is a base class; Rectangle, Square and Parallelogram each inherit Quadrilateral class and are each known as a subclass. Lets assume that Quadrilateral has a Draw() method, which draws a quadrilateral. Evidently you would like to create the same method for each of the subclasses, because you want to draw them as well! You can obviously keep distinct names, but in case of programming, it is advisable to keep relevant names. In this case, the only relevant name is Draw(). But since the base class also owns the very same method, as a subclass you would Override the base class method. What really amazes is the fact that when you want to draw, lets say a rectangle, it calls the Draw() method inside the rectangle class, not anything else! How good is that! Your compiler automatically knows which method you are referring to, so it does not get confused when you call an overriding method.

Before jumping over the code section, we need to understand three related keywords:
  • virtual : This keyword tells the compiler that this method can be overridden by subclasses. The subclasses aren't bound to override this method, but they might want to!
  • override : This tells the compiler that it is overriding its namesake method that can be found in the base class.
  • base : You use this keyword from the overridden method at the subclass when you feel that you want to actually call the method at the base class.
Lets take a look at these keywords in action.

using System;

namespace Spells
{
    class Quadrilateral
    { 
        // some variables, properties and other methods
        public virtual void Draw()
        {
            Console.WriteLine("Drawing a quadrilateral.");
        }
    }
    class Square : Quadrilateral
    {
        // some variables, properties and other methods
        public override void Draw()
        {
            Console.WriteLine("Overridden: Drawing a square.");
        }
    }
    class Rectangle : Quadrilateral
    {
        // some variables, properties and other methods
        public override void Draw()
        {
            Console.WriteLine("Overridden: Drawing a rectangle and also feels like calling base class method.");
            base.Draw();   // this line calls the base class Draw method
        }
    }
    class Program
    {
        public static void Main(string[] args)
        {
            Square sq = new Square();
            sq.Draw();
            Rectangle rect = new Rectangle();
            rect.Draw();
            Quadrilateral quad = new Square();
            quad.Draw();
            Console.Read();
        }
    }
}
Observe line 34 to 37. A square and rectangle type object has been created and when you call the Draw method, it calls the respective overridden method. Line 27 calls the base class implementation of the Draw method. You may choose to call the base class method at your will. At line 38, I have created an object of name Quadrilateral but instantiated it by a subclass called Square. It might seem a little awkward. So what do you think, which Draw method will be called from line 39?
Console output
 As you can see the console output shows that the overridden method at Square has been called. When something like line 38 happens, the compiler calls the lowest descendent of the overridden method, not the ancestor.

Abstract Class: An abstract class like a blueprint model. They cannot be instantiated by themselves, but when you create subclasses from them, you have to instantiate that instead. So what does "blueprint model" interpretation mean here? In abstract classes, there are abstract members that must be overridden by the subclasses and provide functionalities to it. For example, every modern city has building codes, for example buildings cannot be taller than certain heights, they should have sewerage exit and supply of utilities like gas, electricity and water etc. An abstract class is like the building codes, the rules are written there. When someone builds a building (subclass), these rules must be implemented. An abstract class is created by putting the keyword abstract in the class definition. Lets see an easy implementation.

using System;

namespace Spells
{
    abstract class BuildingCodes
    {
        /* no implementation, just a blueprint */
        public abstract void ParkingSpace();
        public abstract bool IsCommercial();
        public abstract bool IsResidential();
    }
    class MyHome : BuildingCodes
    {
        /* must implement all the methods,
         * else a compile time error is generated */
        public override void ParkingSpace()
        {
            // implement logic
        }
        public override bool IsCommercial()
        {
            return false;
        }
        public override bool IsResidential()
        {
            return true;
        }
    }
    class ShoppingMall : BuildingCodes
    {
        /* must implement all the methods,
         * else a compile time error is generated */
        public override void ParkingSpace()
        {
            // implement logic
        }
        public override bool IsCommercial()
        {
            return true;
        }
        public override bool IsResidential()
        {
            return false;
        }
    }
    class Program
    {
        public static void Main(string[] args)
        {
            // BuildingCodes bcodes = new BuildingCodes();    //this is error
            MyHome home = new MyHome();
            ShoppingMall shop = new ShoppingMall();
            Console.WriteLine("Commercial home? {0}\nCommercial Shop? {1}", home.IsCommercial(), shop.IsCommercial());
            Console.Read();
        }
    }
}
Copy and paste this code in your CSharp editor. Go ahead and make line 50 visible. What do you see? An abstract class cannot be instantiated. Then go to any of the subclass, comment-out any of the three overridden methods. Hit F5. A compile time error is generated and asks you to implement an unimplemented method. So why and when should you use an abstract class?
  • When you think that certain things must be implemented in the subclasses.
  • When you want to force programmers to implement something in the subclass.
  • When you have an abstract idea of doing something, but you really don't know how to do them and keep them safe for later implementation.
Sealed Classes and Methods: When you seal-off something, you make sure that it remains intact, no one else touches that thing. Sealed classes and methods basically come up with the same idea. It is quite opposite of the abstract classes. A Sealed class prevents you from subclassing it. You cannot create a subclass of a sealed class. Similarly you cannot override a sealed method. You can seal methods separately in a non-sealed class. But I think sealing method is a redundant idea because a subclass cannot override a base class method unless you make it virtual. This is how you create a sealed class.

sealed class MyClass
{ 
        /* implement code */
}
Go ahead and make the classes in the code snippets above sealed and then try to subclass them. 
You seal a class when you do not want to mess around by creating subclasses of this class. For example when you develop a 3rd party library and you would like to share your project with other developers, often you would love to see others being unable to mess around with certain security-sensitive data and methods. If you want to learn more about sealed classes, the MSDN explains their reason to have such a feature. Click here.

I hope that the advanced CSharp things seemed to you easier and merrier. In the future posts, we shall see something more, something more advanced!