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!

December 16, 2013

C# Collections Part 1 : Array and ArrayList

We have already seen the C# data types and how they are declared and why each of them are internally dealt as an object. In this post, we shall learn about a bunch of these data types, called collections and how these collections are dealt with.

Arrays: In C#, arrays hold a fixed number of elements, all of the same type. For example, if you want a bunch of integer storage, we call them an integer array. If you want to hold a bunch of strings, we call them a string array.
Lets look at the following lines in the code snippet.

int oneInt;
oneInt = 45;
int[] manyInt = new int[5];
Line 1 creates an integer variable and we can assume that somewhere in the memory, the C# compiler creates some space for this variable and stores the value. On line 3, we are creating an integer array. If you are familiar with Java, this is no different than what you have experienced before. It might seem a bit untidy if you are jumping from C or C++. Line 3 is what we are currently interested about. It creates an array of integers, each of them can act similar to the oneInt variable. Somewhere in the memory, the C# compiler creates space for 5 integers in succession. The compiler automatically initializes them with value 0. That is,
  • manyInt[0] initializes to 0.
  • manyInt[1] initializes to 0.
  • manyInt[2] initializes to 0.
  • manyInt[3] initializes to 0.
  • manyInt[4] initializes to 0.
Notice that the numbers inside the square bracket starts at 0 and ends at 1 minus the number that you have specified while defining the array. That means that arrays have 0 based indexes.

In a similar way, you can create arrays of different data types, for example string, char, byte, short, long etc. Lets learn from an example.

using System;

namespace Spells
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] manyString = new string[4];
            manyString[0] = "This is string 1";
            manyString[1] = "This is string 2";
            manyString[2] = "This is string 3";
            manyString[3] = "This is string 4";

            for (int i = 0; i < manyString.Length; i++)
            {
                Console.WriteLine("{0}", manyString[i]);
            }
            Console.Read(); //keeps the console alive
        }
    }
}
As you can see, we have defined an array of type strings. We have used a for loop on line 15. Take a good look on the condition part. manyString.Length will give you the size/length of the array. You can understand from your previous experience that Length in this case is a property. On the outside we may already know the size of the array, but there will be cases when you are not sure about the size of the array. The Length property is really handy in this case.
There is in fact another elegant way of accessing all the items inside an array. Look at the following code. Copy and paste this code instead of the previous for loop.

foreach (string str in manyString)
{
    Console.WriteLine("{0}", str);   
}
We have previously skipped this foreach loop. This special construct of for loop is very handy in handling array items. The "string str" part says that each of the items are individually string type, that's obvious right? The "in manyString" statement says that we are looking for the individual string type "things" inside the manyString array.

We can initialize an array. For example, these two lines are perfectly valid and okay.

int[] myInt = {4,7,2,9,15};
string[] myString = {"One","Two","Three"};
The first line creates an integer array containing 5 elements, while the second line creates a string array containing three elements. The C# compiler will automatically calculate the size of the arrays.

Bounds checking: One of the cool features of C# array is that it can automatically check the array bounds for you. Bounds checking means the C# compiler will keep a notice if you are trying to access an index beyond the size of the array. Keep in mind that in case of arrays, once you declare and define the size of the array, that is how big they can be, you cannot change or modify this size after that. So arrays are fixed in size. It might seem to you a little bit disadvantageous. But once you know that you need certain numbers of elements in an array, the compiler allows them to be contiguous in memory. This is advantageous and very efficient. So bound checking is important. For example, the following code will generate error.

using System;

namespace Spells
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] manyString = new string[4];
            manyString[0] = "This is string 1";
            manyString[1] = "This is string 2";
            manyString[2] = "This is string 3";
            manyString[3] = "This is string 4";

            foreach (string str in manyString)
            {
                Console.WriteLine("{0}", str);   
            }
            manyString[10] = "This is an error";
            Console.WriteLine("{0}",manyString[99]);
            Console.Read(); //keeps the console alive
        }
    }
}
Lines 19 and 20 are both erroneous.

Multidimensional Array: Arrays can have multiple dimensions. Here is an example of a two dimensional array.
Two dimensional Array
You can access any element, for example the 1st element on row 2 can be accessed simply writing multiArray[1,0]. 

Array Functions: You are aware that almost everything in C# is an object. You also know that you can access static methods inside a class without creating object of that class. Having said that, look at the following code snippet.

using System;

namespace Spells
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] myints = { 5, 9, 3, 4, 1, 10, 8 };
            Array.Sort(myints);   //sorts the array
            foreach (int item in myints)
            {
                Console.WriteLine("{0}",item);
            }

            Array.Clear(myints, 0, 3);  //clears the first 3 elements starting at index 0
            foreach (int item in myints)
            {
                Console.WriteLine("{0}", item);
            }

            Array.Reverse(myints);  //reverses the current order of the array
            foreach (int item in myints)
            {
                Console.WriteLine("{0}", item);
            }
            Console.Read(); //keeps the console alive
        }
    }
}
Here is a basic demonstration of some of the built-in facilities that .NET provides for you. Line 9 declares an integer array. Array is a class provided by the .NET framework. This class contains some useful static methods. You obviously understand that static methods can called by the class definition.
  1. Line 10 sorts the array. You can see that sorted output on the following foreach loop.
  2. Line 16 is helpful when you need to reinitialize (make the elements 0 again) a sequence of elements inside the array. The 1st argument takes the name of the array, the 2nd argument asks for the index where we want to start clearing and the 3rd argument takes the number of consecutive elements that we want to clear.
  3. Line 22 reverses the order of array elements.
There are a lot other useful functions that you may explore yourself.

December 15, 2013

Defining Properties

Properties are unique features of C#. They look like data fields, but they have logic behind them. Over the surface, they look like any other member variable. But they act like a member function.

Properties are defined like a field (variable), with the addition of get and set code. Like any other fields or methods, they can use access modifiers.

Let us consider a particular problem. Consider the code below.

using System;

namespace Spells
{
    class Program
    {
        static void Main(string[] args)
        {
            MyClass my = new MyClass();
            my.SetVal(7);
            Console.WriteLine("The value that was set = {0}",my.GetVal());
            Console.Read(); //keeps the console alive
        }
    }

    class MyClass
    {
        private int myint;
        public void SetVal(int val)
        {
            myint = val;
        }
        public int GetVal()
        {
            return myint;
        }
    }
}
We have a class named MyClass. We have a private field and lets assume that its integer type. The methods on line 19 and 23 provides a way to set and get a value from the private field myint. This is neat and pretty basic. If you are familiar with Java, you will see that your IDE provides facilities to implement default code that are usually called getters and setters.

In C#, you can do the same with properties. Properties make your code more readable and manageable. Instead of the methods on line 19 and 23, add the following code inside MyClass.

public int MyIntVal
{
    get { return myint; }
    set { myint = value; }
}
This is what we call a property in C#. MyIntVal is a property. It looks somewhat a mixture of a variable and method declaration. The get code allows you to return the current value of this property. The set code helps you to save the incoming value to the desired variable. Notice the value variable inside the set code. This value is implicit and C# automatically provides the data inside this field. Here is the complete code.

using System;

namespace Spells
{
    class Program
    {
        static void Main(string[] args)
        {
            MyClass my = new MyClass();
            my.MyIntVal = 7;   //triggers the set logic
            Console.WriteLine("The value that was set = {0}",my.MyIntVal);  //triggers the get logic
            Console.Read(); //keeps the console alive
        }
    }

    class MyClass
    {
        private int myint;
        public int MyIntVal
        {
            get { return myint; }
            set { myint = value; }
        }
    }
}
Read the comments on the code, it will help you to get along. Copy and paste or simply write down all the code given. Now remove line 10 and try writing it down again. Once you type my[dot] you will notice a drop down suggestion that Visual Studio is offering.
Properties - MyIntVal
You will see that Visual Studio marks properties differently for you so that they are easily recognizable. In fact Visual Studio provides different visual information for different types of things.

Why use Properties? The obvious reason is the flexibility that it gives. Firstly properties can be calculated on the fly. Secondly properties promote the idea of Encapsulation. It means that you keep your data logic and private things private, encapsulated inside a class. Encapsulation is one of the core features of Object Oriented Programming. Thirdly, properties provide complete control over data field access. The logic is hidden from the consumer class. In our case, the consumer class is the Program class.

Let's play with them a bit more. You can make properties automatic. It means that the property itself will serve the purpose of another private field. For example, look at the following code snippet.

class MyClass
{
    public int MyIntVal
    {
        get;
        set;
    }
}
I have modified MyClass. Go ahead and use it like you see above. It works right? You can also make a property read only or write only. Just remove the get logic, it makes your property write only. Again, just remove set logic, it makes your property read only.

Finally I would like to show you a real life problem and solution using properties.

using System;

namespace Spells
{
    class Program
    {
        static void Main(string[] args)
        {
            MyProduct soap1 = new MyProduct("Irish Spring", 50);
            soap1.Price = 95;
            Console.WriteLine("Price of {0} is {1} BDT", soap1.Name, soap1.Price);

            MyProduct cake1 = new MyProduct("Chocolate Cheese Cake", 10);
            cake1.Price = 710;
            Console.WriteLine("Price of {0} is {1} BDT", cake1.Name, cake1.Price);
            Console.Read(); //keeps the console alive
        }
    }

    class MyProduct
    {
        public string Name
        {
            get;
            set;
        }
        private decimal profit = 0.07m;   // 7% profit on each product
        private decimal wholesale;
        private int units;
        public decimal Price
        {
            get { return wholesale + (wholesale * profit); }
            set { wholesale = value; }
        }
        public MyProduct(string prod, int units)
        {
            Name = prod;
            this.units = units;
        }
    }
}
Observe the following points:
  1. Look at line 9 and 14 inside Main. We create two objects. We already know that once we declare an object, the constructor is called. The constructor at line 35 is called each time. The prod argument is assigned to Name property. This triggers the set logic on line 25. 
  2. Consider line 10 and 14. In each case, the objects individual Price property is used to set a value. So the set logic on line 33 is executed. 
  3. Finally consider line 11 and 15. C# compiler understands that you want to access the values set inside those properties. So the get logic is executed, respectively at line 24 and 32 for Name and Price properties. You already understand that among both the properties, Name is an automatic property. You may also notice that the get logic on Price is working on the fly.
I hope this post makes your C# experience easier and happier. Happy Coding!

December 14, 2013

More on Classes and Access Modifiers : Inheritance

In the previous post, we saw how to create our own class and how to work with it. In this post, we shall explore more on classes and access modifiers like private, protected and public.

One of the most powerful feature of object oriented programming is inheriting information from another class. This feature is commonly named as inheritance. Like real world example, if your parents or your grandparents leave behind something (wealth, land/property) after their death, then as a heir you own that wealth. You are eligible to consume that wealth because you have an inherited relation with the people leaving behind that wealth.

Apply the same on classes. A class can inherit part or all of the information that belongs to another class. Suppose you have a class called A. You write another class B which inherits A. Then we call B a subclass, while A is the base class. Lets learn these things modifying the previous example.

using System;

namespace Spells
{
    class Program
    {
        static void Main(string[] args)
        {
            PublicExam pe1 = new PublicExam("Nabiha", 5, 12, 2002, 2013);

            Console.Read(); //keeps the console alive
        }
    }
    class StudentInfo
    {
        string name;
        int standard;
        int rollnum;
        int dob;    //newly added dob -> date of birth
        static int count = 0;
        public StudentInfo(string name, int stndrd, int roll,int dob)
        {
            this.name = name;
            standard = stndrd;
            rollnum = roll;
            this.dob = dob;
            count++;
        }
        public static int GetCount()
        {
            return count;
        }
    }
    class PublicExam : StudentInfo
    {
        const string PRIMARY = "Primary";
        const string JUNIOR = "Junior";
        const string SECONDARY = "Secondary";
        const string H_SECONDARY = "Higher Secondary";
        int currentyear;
        public PublicExam(string name, int stndrd, int roll,int dob,int year)
            : base(name, stndrd, roll, dob)
        {
            currentyear = year;
        }
    }
}

I have changed the code quite a lot. If you compare the code from the previous post, you will see that a new class called PublicExam now inherits StudentInfo class. Therefore StudentInfo is the base class while PublicExam is a subclass.

Notice line 34. This is the way you inherit a class. In this case, PublicExam class is inheriting StudentInfo class. Now have a good look inside the Main method. We are no longer creating objects of StudentInfo, rather we are interested in objects of PublicExam. In object oriented programming, you already know that when you create an object, you automatically call the constructor. In this case you are calling the PublicExam constructor which takes 5 arguments. This automatically makes a call to the base class constructor StudentInfo. Observe line 42, in this case you are actually specifying how to call the base class constructor. You can choose not to specify in this way; in that case you have to provide a base class constructor that takes no arguments. Go ahead and remove line 42. What do you see? An error that says "Error    1    'Spells.StudentInfo' does not contain a constructor that takes 0 arguments ". You can get rid of this error. For example -
using System;

namespace Spells
{
    class Program
    {
        static void Main(string[] args)
        {
            PublicExam pe1 = new PublicExam("Nabiha", 5, 12, 2002, 2013);

            Console.Read(); //keeps the console alive
        }
    }
    class StudentInfo
    {
        string name;
        int standard;
        int rollnum;
        int dob;    //newly added dob -> date of birth
        static int count = 0;
        public StudentInfo()
        { 
            //necessary codes here
        }
        public StudentInfo(string name, int stndrd, int roll,int dob)
        {
            this.name = name;
            standard = stndrd;
            rollnum = roll;
            this.dob = dob;
            count++;
        }
        public static int GetCount()
        {
            return count;
        }
    }
    class PublicExam : StudentInfo
    {
        const string PRIMARY = "Primary";
        const string JUNIOR = "Junior";
        const string SECONDARY = "Secondary";
        const string H_SECONDARY = "Higher Secondary";
        int currentyear;
        public PublicExam(string name, int stndrd, int roll,int dob,int year)
        {
            currentyear = year;
        }
    }
}

To sum up, if you do not provide a statement like base(...), the compiler will automatically call the base class constructor that has no argument. The constructor from line 21 to 24 takes no arguments. You would probably think that how two methods with the same name can co-exist? They can. This is called constructor overloading. Overloaded methods can have the same name, but they should differ on the number of arguments.
Does this code serve to our purpose? Though the base class constructor is called, but it is actually of no use to us, at least in this case. So we better specify how to call. That was what the first code was doing for us. We revert back to that again. Now we make the classes useful. You possibly have the students date of birth and which standard he/she reads in. Suppose when someone is in standard 5 and at least 10 years old, he/she is eligible to enter Primary exam. How do we do that?

using System;

namespace Spells
{
    class Program
    {
        static void Main(string[] args)
        {
            PublicExam pe1 = new PublicExam("Nabiha", 5, 12, 2000, 2013);

            Console.Read(); //keeps the console alive
        }
    }
    class StudentInfo
    {
        string name;
        int standard;
        int rollnum;
        int dob;    //newly added dob -> date of birth
        static int count = 0;
        public StudentInfo(string name, int stndrd, int roll,int dob)
        {
            this.name = name;
            standard = stndrd;
            rollnum = roll;
            this.dob = dob;
            count++;
        }
        public static int GetCount()
        {
            return count;
        }
    }
    class PublicExam : StudentInfo
    {
        const string PRIMARY = "Primary";
        const string JUNIOR = "Junior";
        const string SECONDARY = "Secondary";
        const string H_SECONDARY = "Higher Secondary";
        int currentyear;
        public PublicExam(string name, int stndrd, int roll,int dob,int year): base(name,stndrd,roll,dob)
        {
            currentyear = year;
        }

        public string WhichExam()
        {
            int age = currentyear - dob;   //the current age
            if (standard == 5 && age >= 10)
            {
                return PRIMARY;
            }
            else if (standard == 8 && age >= 13)
            {
                return JUNIOR;
            }
            else if (standard == 10 && age >= 16)
            {
                return SECONDARY;
            }
            else if (standard == 12 && age >= 18)
            {
                return H_SECONDARY;
            }
            else
            {
                return "No exams!";
            }
        }
    }
}
This code will let you down. You will see that dob and standard variables aren't recognized inside the function WhichExam. Your Visual Studio should say that these variables aren't accessible because of protection level. But hey! Didn't we just inherit everything from StudentInfo? True. Then what's wrong? In C#, everything by default is private. So all the variables inside StudentInfo are private and are only accessible inside StudentInfo class. So how do we access these variables? There are two possible ways -
  • Make the variables public.
  • Make the variables protected.
I will go with solution no. 2. Making the variables public isn't an intelligent solution. Because in that way, you expose your variables to the outer world that aren't quite necessary to them. You also make them vulnerable because you can accidentally modify their values anywhere else! See the working code using protected modifier on line 19 and 21.

using System;

namespace Spells
{
    class Program
    {
        static void Main(string[] args)
        {
            PublicExam pe1 = new PublicExam("Nabiha", 5, 12, 2000, 2013);
            PublicExam pe2 = new PublicExam("Abrar", 2, 22, 2003, 2013);
            Console.WriteLine("{0} will sit for {1}",pe1.GetStudentName(),pe1.WhichExam());
            Console.WriteLine("{0} will sit for {1}", pe2.GetStudentName(), pe2.WhichExam());
            Console.Read(); //keeps the console alive
        }
    }
    class StudentInfo
    {
        string name;
        protected int standard;
        int rollnum;
        protected int dob;    //newly added dob -> date of birth
        static int count = 0;
        public StudentInfo(string name, int stndrd, int roll,int dob)
        {
            this.name = name;
            standard = stndrd;
            rollnum = roll;
            this.dob = dob;
            count++;
        }
        public static int GetCount()
        {
            return count;
        }
        public string GetStudentName()
        {
            return name;
        }
    }
    class PublicExam : StudentInfo
    {
        const string PRIMARY = "Primary Exam";
        const string JUNIOR = "Junior Exam";
        const string SECONDARY = "Secondary Exam";
        const string H_SECONDARY = "Higher Secondary Exam";
        int currentyear;
        public PublicExam(string name, int stndrd, int roll,int dob,int year) : base(name,stndrd,roll,dob)
        {
            currentyear = year;
        }

        public string WhichExam()
        {
            int age = currentyear - dob;   //the current age
            if (standard == 5 && age >= 10)
            {
                return PRIMARY;
            }
            else if (standard == 8 && age >= 13)
            {
                return JUNIOR;
            }
            else if (standard == 10 && age >= 16)
            {
                return SECONDARY;
            }
            else if (standard == 12 && age >= 18)
            {
                return H_SECONDARY;
            }
            else
            {
                return "No exams!";
            }
        }
    }
}
Aha! Your code is ready to run. Hit F5 and see the output. Finally, you will notice that you can access methods from the base class by an object of the subclass. Subclass objects can have access to public methods inside the base class.

I hope the concepts of inheritance, access modifiers and how to control access to members and methods are quite clear. Just play with them, edit/modify these codes and see what you are allowed to do and what not.

December 11, 2013

Classes and Objects

We already know that C# is an Object Oriented Programming language. We have seen that every variable that we declare in our program are objects. A C# program at the heart is an object; you probably have noticed that your code is inside a class named Program. Inside that class, you declare some other variables or objects or methods and you do your stuff.

So what we understand from this is that C# is inherently an object oriented programming language. We shall discuss about classes and objects in this post. We shall also go through some important aspects that are related to classes and objects.

Classes group together some data and logic with those data. If you have some data and logic which are closely related, the idea is to keep them together and bundle up. While you bundle things up, you will want to control how you want to modify these data. So classes actually provide you a neat and cleaner experience of doing these things.
Interaction between classes
Classes can interact with each other. By all means you will want to modify/update your data from other end. This is how you make your program dynamic.

A class is actually a blueprint or model of what an object looks like, what this object is capable of. It tells you what kinds of data this object is interested in, what kinds of task this object can perform. Suppose someone makes the design of how a laptop looks like, the blueprint of a laptop is a class. When you make an actual product from that blueprint, its an object from that design. A red covered laptop is an object, so is a silver covered laptop. Your blueprint lets you know what each of them has in basics.

.NET framework provides you a whole bunch of useful classes. You can use them for many different purposes. You can declare your own class. Classes essentially have two major types of members.
  1. Fields and Properties
  2. Methods (or functions)
The fields and properties are what the class (read object) holds and works with. Methods provide a way of doing stuffs with these fields and properties. You can manipulate or use the fields and properties via these methods.

Let us consider a system where we hold on some data of a student in a school. If we keep it simple, lets say we deal only with his/her name, the standard he/she reads in and his/her roll number. You might have noticed that we have already prepared our fields.
  1. Name
  2. Standard he reads in
  3. Roll number
This is a simple model of our class.

class StudentInfo
{
    string name;
    int standard;
    int rollnum;
}
How do we manipulate these data? How do we put data in the first place? Lets take a look into the following code.
using System;

namespace Spells
{
    class Program
    {
        static void Main(string[] args)
        {
            StudentInfo student1 = new StudentInfo("Mahmud", 8, 21);
            Console.Read(); //keeps the console alive
        }
    }
    class StudentInfo
    {
        string name;
        int standard;
        int rollnum;
        public StudentInfo(string name, int stndrd, int roll)
        {
            this.name = name;
            standard = stndrd;
            rollnum = roll;
        }
    }
} 

Line 9 creates an object of the class StudentInfo. If you are familiar with other object oriented languages, you are familiar with this line. This is the way we create an object. And you can see, while creating the object, we are passing three values that we would like to define in our object of type StudentInfo. In a nutshell, the object student1 belongs to a student whose name is Mahmud.
This class functionally does nothing. It can't communicate with others. So how do we make it to speak? Lets try out this.

using System;

namespace Spells
{
    class Program
    {
        static void Main(string[] args)
        {
            StudentInfo student1 = new StudentInfo("Mahmud", 8, 21);
            StudentInfo student2 = new StudentInfo("Nabiha", 2, 5);
            Console.WriteLine("{0}'s roll number is {1}",student1.getName(),student1.getRollNum());
            Console.WriteLine("{0}'s roll number is {1}", student2.getName(), student2.getRollNum());
            
            Console.Read(); //keeps the console alive
        }
    }
    class StudentInfo
    {
        string name;
        int standard;
        int rollnum;
        public StudentInfo(string name, int stndrd, int roll)
        {
            this.name = name;
            standard = stndrd;
            rollnum = roll;
        }
        public int getRollNum()
        {
            return rollnum;
        }
        public string getName()
        {
            return name;
        }
    }
}
You will notice that we create yet another object, but notice that when we ask for the same piece of information from both of the objects, they give us their own individual information.For example, consider line 11 and 12, the output that we are showing, we don't know who actually is student1 or student2 object. So we provided some functions inside the StudentInfo class. Notice that we call the same function from two different objects, so we are getting two different values. Congratulations! You have seen the power of using objects. So you see, you don't have to define different functions for individual records, all you do is code once and use it again and again, perhaps using different objects.

You can create as many objects as you like, as many useful methods as you need. Notice that, while writing the code, when you type the object name and hit a period(dot .) the Visual Studio editor will provide you some options. Aha! You don't see the fields name, do you? What do you understand from this? In C#, the default access modifier is private. What are access modifiers? In C# there are different modes which you can specify how your fields or methods are visible to the outside world. In our case, the string variable name, integer variable  standard and rollnum are private to the class. It means that you can only access them when you are inside the class. For example, from line 25 to 35, you accessed them, returned their values to outside world. You can manipulate here. You cannot manipulate these variables from outside.

Hit the dot [.] again after the object name, now notice that you are able to see the methods getName() and getRollNum(). You can access them because their access modifier is public! Had they been private, they would have been inaccessible from where we accessed earlier.

Constructor: Finally, the one and only constructor. The name of the constructor should be that of the class name. It should be declared public. A constructor should not return anything. A constructor can take any number of arguments. If you do not provide a constructor, your compiler automatically puts (I mean not visible to you!) a default constructor that takes no argument and does nothing. 

Finally let's look into another method in the slightly modified code.

using System;

namespace Spells
{
    class Program
    {
        static void Main(string[] args)
        {
            StudentInfo student1 = new StudentInfo("Mahmud", 8, 21);
            StudentInfo student2 = new StudentInfo("Nabiha", 2, 5);
            
            Console.WriteLine("{0}'s roll number is {1}",student1.GetName(),student1.GetRollNum());
            Console.WriteLine("{0}'s roll number is {1}", student2.GetName(), student2.GetRollNum());
            Console.WriteLine("{0} students are available", StudentInfo.GetCount());
            
            Console.Read(); //keeps the console alive
        }
    }
    class StudentInfo
    {
        string name;
        int standard;
        int rollnum;
        static int count = 0;
        public StudentInfo(string name, int stndrd, int roll)
        {
            this.name = name;
            standard = stndrd;
            rollnum = roll;
            count++;
        }
        public int GetRollNum()
        {
            return rollnum;
        }
        public string GetName()
        {
            return name;
        }
        public static int GetCount()
        {
            return count;
        }
    }
}
Static fields and methods: Suppose you want to get a count of how many students are available in your StudentInfo class. This count should be kept in a variable which should not get changed (re-initialized) when new objects are created. Fortunately the static variables are really good in this purpose. Notice the static integer variable on line 24. It is initialized with default value 0. Each time a new object is created, the constructor is called and a count++ occurs, which increments the value. 
Now notice the method GetCount(). Its access modifier is public static. What does that mean? public allows you to call this method from outside. A static method is something special. Go ahead and try to access it using one of the objects (student1 or student2). This method is inaccessible, right? A static method is accessible from the class definition, it means that in order to access a static method, you don't need to create an object, you can access it using the name of the class itself.

I hope these things make sense to you after reading this post. Happy coding!