Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

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!

December 22, 2013

Exploring Strings

Now that we have basic idea about string objects and arrays, we can safely explore string methods. One of the core C# programming quality is to be able to manipulate strings. And to do that, you have to know different built-in .NET methods and their usage.

In this post, we shall also see some of the un-managed bugs that are frequently found around string codes. We shall also see how the same code can behave differently when certain conditions are changed.

Before we start, open this link in a different tab.

Compare two strings: To compare two strings, you can use the Compare method. On the given link, you will find that there are around 8-10 overloaded Compare methods. If you are not familiar with method overloading, go back and see the post on classes and objects. The Compare method returns integer value.
If the value is equal to zero, then the two strings are equal. If the value is less than zero, the first string is less than the second. The opposite happens when the value is greater than zero.

However, we are more interested about which overloaded method to use and why are there so many overloaded methods. It apparently seems lie all of them perform in the same way. But you can twist them based on your necessities. Below is a demonstration of some of the overloaded methods and their purposes.

using System;

namespace Spells
{
    class Program
    {
        static void Main(string[] args)
        {
            string str1 = "thoughts";
            string str2 = "thoughts";
            if (string.Compare(str1, str2) == 0)  // 1
                Console.WriteLine("1. Equal");
            else
                Console.WriteLine("1. Not equal");
            str2 = "tHoughTs";                      // change the cases
            if (string.Compare(str1, str2) == 0)    // 2
                Console.WriteLine("2. Equal");
            else
                Console.WriteLine("2. Not equal");
            if (string.Compare(str1, str2, true) == 0)  // 3
                Console.WriteLine("3. Equal");
            else
                Console.WriteLine("3. Not equal");
            str1 = "æ";
            str2 = "ae";
            if (string.Compare(str1, str2, StringComparison.InvariantCulture) == 0)        // 4
                Console.WriteLine("4. Equal");
            else
                Console.WriteLine("4. Not equal");
            if (string.Compare(str1, str2, StringComparison.Ordinal) == 0)        // 5
                Console.WriteLine("5. Equal");
            else
                Console.WriteLine("5. Not equal");
            Console.Read();
        }
    }
}
Notice that line 11 and 16 are exactly the same method. I have changed one of the strings to see the output. If you run the code, you will also notice that the outputs are different, which is quite evident. Line 20 however uses a different overloaded method. The third parameter is a boolean parameter specifying if you want to make a case-sensitive or insensitive comparison. The default (without third parameter) is a case-sensitive comparison. However, the best practice is to specify it in the code, in that way, when others read your code, its clear to them what you are actually trying to do!

I have changed string 1 and 2 on line 24 and 25 to something else. Its a phonetic symbol. I made up my mind to test what StringComparison enumerator does as a third parameter. Line 26 and 30 will surprise you, because if you see the output, the 4th comparison will show "Equal" while the 5th will show "Not equal". The Ordinal simply makes a direct comparison on Unicode characters. If your goal is to check whether there is anything different between the two strings, go with Ordinal. On the otherhand, InvariantCulture knows about special rules on phonetics and languages.
Recommended: Use this method when you are trying to compare strings for sorting purpose. Comparison 3 and 5 (in the code snippet line 20 and 30 respectively) are recommended while 1 and 2 are highly discouraged.

Equality: Comparing two strings and checking for equality are two different things and should not be confused. When you compare strings, your interpretation is to find out which among the two should be higher in ordered sequence. But in equality check, you only check whether the two string objects are equal or not.
The following code snippet is a simple implementation of Equal method. Though both the interpretation results the same output, the 2nd way is nice, neat and helpful.

string str1 = "thoughts";
string str2 = "thoughts";
if (str1.Equals(str2))
    Console.WriteLine("Equal");
else
    Console.WriteLine("Not equal");
if(string.Equals(str1,str2))
    Console.WriteLine("Equal");
else
    Console.WriteLine("Not equal");
That the 2nd way is helpful, we shall see that in a couple of examples.

using System;

namespace Spells
{
    class Program
    {
        static void Main(string[] args)
        {
            string str1 = "thoughts";
            string str2 = "thoughts";
            if(string.Equals(str1,str2))      // 1
                Console.WriteLine("1. Equal");
            else
                Console.WriteLine("1. Not equal");
            str2 = "ThouGhts";
            if (string.Equals(str1, str2, StringComparison.OrdinalIgnoreCase))      // 2
                Console.WriteLine("2. Equal");
            else
                Console.WriteLine("2. Not equal");
            if (string.Equals(str1, str2, StringComparison.Ordinal))      // 3
                Console.WriteLine("3. Equal");
            else
                Console.WriteLine("3. Not equal");
            Console.Read();
        }
    }
}
Recommended: Line 16 and line 20 are recommended. They make your code distinct and precise. They will make an unambiguous interpretation to whoever watching your code whether you are ignoring cases or not.

The Culture Issue: At this point you might be wandering what this culture means when you look into StringComparison enumeration. The culture essentially means the regional language. Go to your control panel -> clock, language and region -> region -> location tab. The default is United States, unless you change it by yourself. This will be the current culture in your pc. Now when you create a program, then the default string operations are done based on current culture, unless you state which culture you want explicitly. You may like to read further on these issues directly from MSDN library. This is a code that I have directly used from this link.

using System;
using System.Globalization;
using System.Threading;

namespace Spells
{
    class Program
    {
        public static void Main(string[] args)
        {
            string[] values = { "able", "ångström", "apple", "Æble", 
                         "Windows", "Visual Studio", "Thoughts and Spells" };
            Array.Sort(values);
            DisplayArray(values);

            string originalCulture = CultureInfo.CurrentCulture.Name; // save the current culture
            // Change culture to Swedish (Sweden).
            Thread.CurrentThread.CurrentCulture = new CultureInfo("sv-SE");
            Array.Sort(values);
            DisplayArray(values);

            // Restore the original culture.
            Thread.CurrentThread.CurrentCulture = new CultureInfo(originalCulture);

            Console.Read();
        }

        private static void DisplayArray(string[] values)
        {
            Console.WriteLine("Sorting using the {0} culture:",
                              CultureInfo.CurrentCulture.Name);
            foreach (string value in values)
                Console.WriteLine("   {0}", value);

            Console.WriteLine();
        }
    }
}
This is the output console.

Here is a link of all the cultures [All cultures]. I hope you understand why the same code can perform differently when the current culture changes. So it is advisable and recommended that when linguistics and localization of your application do matter, the choice of default culture and explicitly specifying the culture matters.

Searching a character or a string: Searching for a character or an entire string inside a string is a regular string handling task. Below is a code snippet that shows you three different methods that you can use while searching for a string instance.

using System;

namespace Spells
{
    class Program
    {
        public static void Main(string[] args)
        {
            string str = "This is a post about strings. It will help you to learn more about strings.";

            Console.WriteLine("Character 'a' at {0}", str.IndexOf('a'));
            Console.WriteLine("String 'is' at {0}", str.IndexOf("is"));
            Console.WriteLine("String 'is' at {0}", str.IndexOf("is", 4));
            Console.WriteLine("String 'to' at {0}", str.IndexOf("to", StringComparison.CurrentCulture));
            Console.WriteLine("String 'is' at {0}", str.IndexOf("is", 4, StringComparison.Ordinal));
            Console.WriteLine("String 'String' at {0}",str.IndexOf("String",StringComparison.OrdinalIgnoreCase));

            Console.WriteLine("Last occurence of 'String' at {0}", str.LastIndexOf("String", StringComparison.OrdinalIgnoreCase));
            Console.WriteLine("Last occurence of 'String' at {0}", str.LastIndexOf("String", 60, StringComparison.OrdinalIgnoreCase));

            Console.WriteLine("Starts with the word 'this'? {0}", str.StartsWith("this"));
            Console.WriteLine("Starts with the word 'this'? {0}", str.StartsWith("this", StringComparison.OrdinalIgnoreCase));

            Console.Read();
        }
    }
}

The IndexOf method returns the zero-based index of the first occurrence of a character or a string. What is the difference between line 11 and 12? At line 11, we search for a character only. The default interpretation for IndexOf method is StringComparison.CurrentCulture. However, note carefully that the overloaded method for searcheing a character does not allow you to specify StringComparison explicitly. You are allowed to specify StringComparison in case of string searches only, as in line 14 to 16. MSDN recommends that it is best to use the overloaded methods that allows explicit declaration of StringComparison. This ensures code clarity and ease of debug.
The LastIndexOf method at line 18 and 19 is similar to IndexOf method. It returns zero-based index of the last occurrence of a string or a character.
The StartsWith method helps you to search if the given string has any particular starting string. Among line 21 and 22, the one with StringComparison parameter is recommended. This clears the confusion to other programmers if you are ignoring or considering cases.

Splitting a string: Often you will find yourself in a situation where you would want your program to consider each word individually. Splitting comes to the rescue. Fortunately the Split method returns an array of string after splitting the string.

using System;

namespace Spells
{
    class Program
    {
        public static void Main(string[] args)
        {
            string str = "Learn C# @ www.thoughts-n-spells.blogspot.com.";
            string[] broken = str.Split(' ');             // 1
            Display(broken);

            char[] splitters = { ' ', '@', '.' };
            string[] broken2 = str.Split(splitters);      // 2 
            Display(broken2);

            string[] broken3 = str.Split(splitters,StringSplitOptions.None);      // 3 
            Display(broken3);

            string[] broken4 = str.Split(splitters, StringSplitOptions.RemoveEmptyEntries);      // 4 
            Display(broken4);

            Console.Read();
        }
        private static void Display(string[] toDisplay)
        {
            foreach (string item in toDisplay)
            {
                Console.WriteLine("{0}", item);
            }
            Console.WriteLine("============");
        }
    }
}
The first parameter of Split is either a character array or string array specifying what to remove or split upon. In this case, I have used character array considering single character as delimiter to split my string. If you have a single character to use as delimiter, use the one at line 10. If you have multiple characters to shove off, use it like line 13 and 14.
If two delimiters are adjacent, or a delimiter is found at the beginning or end of this instance, the corresponding array element contains Empty.
The Empty string means a string with length 0. Go ahead and look at the output for line 14 and 17.
Look at the red marks on the console image. I have marked the places where we have found empty strings as output. If both the methods at line 14 and 17 output the same thing, then which one is recommended? Obviously line 17. In that way, you let yourselves and others know that you are allowing empty strings as output! If you want to eliminate empty strings from the return array, go ahead and look at line 20. The StringSplitOptions.RemoveEmptyEntries allows you to remove empty strings. As you can see, the last output contains a returned string array that has no empty strings.

The Regex.Split method: Often you would find the necessity to find patterns and split based on patterns. The Regex.Split method comes handy in these tasks. Functionalities are almost similar to the Split method, except the fact that Regex.Split is flexible and allows you more freedom to play with strings.

using System;
using System.Text.RegularExpressions;

namespace Spells
{
    class Program
    {
        public static void Main(string[] args)
        {
            /* remove all the spaces */
            string str = "7 + 4 - 2 = 3 * 3";
            string[] separated = Regex.Split(str, @"\s+");
            Display(separated);
            /* remove non-digit characters */
            str = "10 tablets, 25 handsets, 33 laptops";
            string[] numbers = Regex.Split(str, @"\D+");
            Display(numbers);
            /* remove all the lowercase alphabets */
            str = "Awer145rwrKcx777sdFew45xcvdfg111";
            string pattern = @"[a-z]+";
            string[] magic = Regex.Split(str, pattern);
            Display(magic);
            /* remove all aplphabets ignoring cases */
            string[] moreMagic = Regex.Split(str, pattern, RegexOptions.IgnoreCase);
            Display(moreMagic);

            Console.Read();
        }
        private static void Display(string[] toDisplay)
        {
            foreach (string item in toDisplay)
            {
                Console.WriteLine("{0}", item);
            }
            Console.WriteLine("============");
        }
    }
}
Go ahead and hit F5 and see the output.

Leading or trailing spaces bothering you? .NET provides 3 classy methods to remove leading and trailing spaces.

using System;

namespace Spells
{
    class Program
    {
        public static void Main(string[] args)
        {
            string str = "   Spaces at front and spaces at the back.    ";
            Console.WriteLine("<>{0}<>", str);
            Console.WriteLine("<>{0}<>", str.TrimStart());
            Console.WriteLine("<>{0}<>", str.TrimEnd());
            Console.WriteLine("<>{0}<>", str.Trim());

            Console.Read();
        }
    }
}

The Trim methods are useful when you receive data over a network or when you read files. In that way, you can remove unnecessary leading or trailing spaces. 

I have tried to show some of the fundamental string methods and their usages. I have also tried to show overloaded methods that can leave certain traces of bugs, whose interpretations could be different under different contexts. Lastly I have also tried to show some recommended practices which can improve code clarity and unambiguity.

December 18, 2013

C# Collections Part 3 : List, Hashtable and Dictionary

This post is dedicated to some phenomenal data structures that are available in C#. In most of your projects, you will find that any of these 3 data structures prove to be tremendously useful under any circumstance.

List: If you are familiar with ArrayList, you are already halfway down to understanding Lists. List is a generic class. The actual notation for a List class is List<T>. It's a template for any object type. Lets jump over to the code and see how to use a list.

using System;
using System.Collections.Generic;

namespace Spells
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> myStringList = new List<string>();
            myStringList.Add("Thoughts");
            /* myStringList.Add(1);    // this is error because it only support string type now */
            myStringList.Add("Spells");

            Console.WriteLine("Number of items {0}", myStringList.Count);
            foreach (string item in myStringList)   
            {
                Console.WriteLine("{0}", item);
            }

            myStringList.Insert(1, "Collections");   //inserts at index 1

            Console.WriteLine("Number of items {0}", myStringList.Count);
            foreach (string item in myStringList)
            {
                Console.WriteLine("{0}", item);
            }

            myStringList.Remove("Spells");   // removes the element "Spells"
            myStringList.RemoveAt(0);      // removes the element at index 0

            Console.WriteLine("Number of items {0}", myStringList.Count);
            foreach (string item in myStringList)
            {
                Console.WriteLine("{0}", item);
            }

            Console.Read(); //keeps the console alive
        }
    }
}
You will notice that the using statement at line 2 is slightly different than what we saw in the earlier posts. Here is the output console.
Console output
  1. Line 10 is the creation of a list object. Inside the angle bracket <> we have specified that our list object should contain only string data types. For the same reason, line 12 will generate an error because you are trying to add an integer object. This is a basic difference between List<T> and ArrayList.
  2. Added two string objects on line 11 and 13.
  3. Line 15 shows how many items are currently inside the list. Once you run this program, you will notice that there are 2 string items inside. Line 16 to 19 prints out each items. Pay attention! You know for sure that the list object contains only string objects. The foreach construct iterates through each item. You could not do that in ArrayList. Because ArrayList is not generic class. You would have to use object class to iterate each item inside the arraylist. This is another difference between ArrayList and List<T>.
  4. Line 21 is another way of adding items to the list. But you should be careful and know the difference between insert and add methods. The Add method adds items at the back of the list. But Insert method can add items anywhere in the list. By inserting an item anywhere in the middle, you slide down rest of the items and insert the current item at the desired index. As you can see in the output console, the number of items increased by 1 and item "Spells" slided down to make way for "Collections" at index 1.
  5. You can delete items just as you insert or add the items. Line 29 and 30 uses two different methods, one specifying the string items directly, while another trying to delete the item at the specific index. So what happens when you have duplicate items? Yes obviously List<T> can hold duplicate items. But which one gets deleted? Or both? The item belonging to the lower index gets deleted.
The bottom line is, List<T> is more preferable than ArrayList. Because its type safe. By type safe, it means that you do not have to worry about boxing and unboxing objects. If you are not familiar with boxing and unboxing, go ahead and read this post.

Hashtable: A Hashtable data structure is essentially a Dictionary. Currently Hashtable is less preferable than a more generic Dictionary<Tkey,Tvalue> class. However, for the sake of understanding data structures, I have decided to cover it here.

Dictionaries are used to associate values with a key. A key-value pair item helps you to look-up a value very quickly and its efficient as well. Be aware that keys must be unique. There is no sense of order in Dictionaries. The Hastable class is a remarkable example of Dictionary in C#. Lets jump over to a code snippet.

using System;
using System.Collections;

namespace Spells
{
    class Program
    {
        static void Main(string[] args)
        {
            Hashtable myHt = new Hashtable();

            myHt.Add("CSE 101", "Introduction to C");  // string key and string value
            myHt.Add("CSE 201", "Concepts of OOP: C# and .NET");  // string key and string value
            myHt.Add(5, "The key is an integer");   // integer key and string value
            myHt.Add("String key", 7);   // string key and integer value
            myHt["another key"] = "another way to insert value";  // string key and string value

            Console.WriteLine("Number of items {0}", myHt.Count);
            Console.WriteLine("Do you have CSE 201 key? {0}", myHt.ContainsKey("CSE 201"));
            myHt.Remove("String key");   // removes the key and the value
            Console.WriteLine("Do you have the value 7 ? {0}", myHt.ContainsValue(7));

            Console.Read(); //keeps the console alive
        }
    }
}
A Hashtable object is created just like you create objects for any other classes. On line 10 we create a Hashtable object. The Hashtable class is not a generic type. As much as that is a concern, you can create entries in many different possible ways as shown from line 12 to 16. Any data type can be the key and any data type can be the value, as long as the keys remain unique. Here is a visual console output window.
Console Output for Hashtable
Line 18 displays the number of current items inside the Hashtable. There are certain useful methods. Line 19 uses a method ContainsKey that takes as argument a key. It's a boolean method, it returns true if the key is in the table, else it will return false. We remove an item that we inserted at line 15 on line 20. That is why the output on line 21 shows that it cannot find the value 7 inside the Hashtable.

Dictionary<Tkey,Tvalue>: The only thing different here is that this class is generic. You can specify which data type is the key and which data type is the value. That way, you won't be able to mess around different data types at the same time. The boxing and unboxing issue is present here as well. There are other differences as well which are quite advanced, but worth knowing. We keep that until the end of this post.

Moving forward, lets see an example code snippet.

using System;
using System.Collections.Generic;

namespace Spells
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, string> courseTable = new Dictionary<string, string>();

            courseTable.Add("CSE 101", "Introduction to C");
            courseTable.Add("CSE 201", "Concepts of OOP: C# and .NET");
            courseTable.Add("CSE 207", "Data Structures and Algorithms");

            Console.WriteLine("Number of items {0}", courseTable.Count);
            foreach (KeyValuePair<string,string> pair in courseTable)
            {
                Console.WriteLine("Course Code: {0}, Course Title: {1}", pair.Key, pair.Value);
            }

            if (courseTable.ContainsKey("CSE 101"))
            {
                courseTable["CSE 101"] = "Introduction to Structured Programming";
            }
            if (!courseTable.ContainsValue("Database Systems"))
            {
                courseTable["CSE 301"] = "Database Systems";
            }

            Console.WriteLine("Number of items {0}", courseTable.Count);
            foreach (KeyValuePair<string, string> pair in courseTable)
            {
                Console.WriteLine("Course Code: {0}, Course Title: {1}", pair.Key, pair.Value);
            }
            
            Console.Read(); //keeps the console alive
        }
    }
}
I preferred to create a course table data structure so I opted for a string key and string value. The basic idea is you can create differently as you wish.
Console Output for Dictionary
  • Line 10 shall prove convincingly to you why Dictionary class is quite safer than Hashtable. You are not able to mess with types in Dictionary.
  • Line 12 to 14 creates 3 entries in the courseTable.
  • Line 16 to 20 are console outputs. Line 17 will give you something new to learn. .NET provides to you a safer way to iterate each key-value pair. You should keep in mind that the data types inside the angle bracket < > should match with the data types of the Dictionary object. The Key and Value properties enables you to work with these items.
  • While you decide to create new items or edit an existing items, its always safer to check if that item exists or not. That is what we are doing at line 22 and 26. If it happens that you are trying to edit/remove an item that never existed, then the C# compiler will throw an exception, unlike Hashtable that returns null in these cases. 
  • You can follow similar manners while removing an item.
There are some thread safety issues with Hashtable and Dictionary classes. Hashtable provides a thread safe environment where concurrent reads are handled nicely. In case of Dictionary, you will have to synchronize your reads and writes if you have multiple threads reading/writing them. The dictionary offers a bit more faster lookups because of value types.

I hope this post makes sense to you. Play with them and discover the undiscovered! Happy Coding!

December 17, 2013

C# Collections Part 2 : Stack and Queue

Stacks and queues are like arrays or ArrayList. But they are different when it comes to the order of accessing the items. They operate on a different paradigm; namely push-on and pop-off.

Stack: Stack is an abstract data type. The idea of stack is basically in harmony with that we see at restaurants. The plates are piled on to each other. When you need a plate, you just take the one on the top, you do not pull out one from the middle. Again, when the pile is empty, the first plate to be on the pile is the one located at the bottom. The latest plate on the pile is the one situated at the top. So the basic notion associated with Stack operation is Last in First out or LIFO. The earliest element is at the bottom, while the newer elements take position near the top.

Let's jump over to code snippet and analyze a stack operation.

using System;
using System.Collections;

namespace Spells
{
    class Program
    {
        static void Main(string[] args)
        {
            Stack myStack = new Stack();
            myStack.Push("string 1");  // pushing a string type
            myStack.Push(13);    // pushing an integer
            myStack.Push('A');    // pushing a character type

            Console.WriteLine("Current number of items {0}", myStack.Count);

            object obj = myStack.Pop();   // pops of the top item
            Console.WriteLine("The top item was {0}", obj);

            Console.WriteLine("Current number of items {0}", myStack.Count);

            obj = myStack.Peek();   // returns the top item without replacing it
            Console.WriteLine("The top item was {0}", obj);

            Console.WriteLine("Current number of items {0}", myStack.Count);
            
            myStack.Clear();     // deletes all the existing element
            Console.WriteLine("Current number of items {0}", myStack.Count);
            Console.Read(); //keeps the console alive
        }
    }
}
In this particular example, you can see some very basic stack operations like pushing an item in the stack, popping the item, observing the top item of the stack without replacing it and obviously counting the total number of elements on the stack.
  1. Consider line 2. Like ArrayList, the Stack class belongs to Collections class under System namespace.
  2. Line 10 creates a stack object. Since it's an object, we have some classy .NET methods to explore. 
  3. The Push method adds object items in the stack. Take a good note that the added items are object type, so you can add any types of object inside the same stack. This is what we are doing from line 11 to 13.
When we push items inside the stack, the last item remains at the top.
Stack items after line 13
 Line 15 and onwards are interesting. Here is a visual output of the above program.
Stack operation output
The first console output belongs to line 15. As you can see, the current number of items is 3. On line 17, we Pop an item. Keep in mind that a popped item is no more a part of the stack. The popped item is saved in an object instance since all the items are basically objects of different data types. Saving the item in an object instance is an intelligent solution because its generic and you never know what is currently the topmost item. Line 18 prints that item and as you can see, the item was the character 'A'. Line 20 gives the current count of the items and you have rightly guessed that, there are 2 items left.

Line 22 tries to grab the topmost item without deleting it. This method is called Peek. You can see that line 25 shows an unchanged count of items. Finally on line 27, you clear all the current items. So the item count is 0.

Stacks are useful in many different algorithms. Its a beautiful data structure and often helpful in searching algorithms.

Queue: Queues are similar to stack, but the ordering is different. You can think of queues as the line in front of a bank counter; where the person standing at the front gets the service first. New entries take position from the end of the line. So the queues follow the notion First in First out or FIFO. Let's jump in to the code.

using System;
using System.Collections;

namespace Spells
{
    class Program
    {
        static void Main(string[] args)
        {
            Queue qq = new Queue();
            qq.Enqueue("string 1");  // inserts a string object
            qq.Enqueue(5);      // inserts an integer object
            qq.Enqueue('M');     // inserts a character object

            Console.WriteLine("Current number of items {0}", qq.Count);
            
            object obj = qq.Peek();
            Console.WriteLine("Top of the queue item '{0}' ",obj);

            obj = qq.Dequeue();
            Console.WriteLine("Current number of items {0} and the dequeued item was '{1}' ", qq.Count, obj);

            obj = qq.Peek();
            Console.WriteLine("Top of the queue item '{0}' ", obj);
            Console.Read(); //keeps the console alive
        }
    }
}
Things are pretty similar to Stacks. You create a Queue object using the Queue class that .NET provides for you. Like stacks, queues also take items as objects.
  1. From line 11 to 13, the Enqueue method inserts items as objects inside the queue. You can understand the flexibility that C# offers because you are able to insert many different data types.
  2. The Count property returns the number of items currently inside the queue object.
  3. The Peek method on line 17 ensures that you are able to see the top/front of the queue, without destroying the object.
  4. The Dequeue method on line 20 actually destroys the object at the front. C++ doesn't allow you to see the destroyed object, while in C# you can do that comfortably. Consider line 21 where you will see a change of item count.
Here is my console window output.
Queue operation output

Queues are also helpful in searching algorithms. You may also need queues when you program a real life Queue Management software for some organizations.

Go ahead and play with these codes. Who knows, you could find gems in them!