Showing posts with label objects. Show all posts
Showing posts with label objects. Show all posts

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 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!

December 6, 2013

Data Types, Constants and Enumerations

In the last post, we discussed about variables, conditional statements and switch statements. I also mentioned that we shall continue discussion on variables.

So in this post, we shall discuss more on variables, for example data types, constants and enumerators.

By now we know how to declare a variable. You have to specify the data type followed by a variable name. C# provides a large and useful collection of data types. There are primitive data types.
C# Data Types
Image courtesy: MSDN Library

Objects: Almost everything in C# is an object. This is really cool and neat. All the primitive data types that we have seen above are treated as objects in C#. Note that we shall discuss about objects as a concept in later posts.
As you can see in the image above, the column .NET class gives the class name to which these data types are related to. Interestingly, these classes are directly derived from the base class System.Object. Take a look at the following code snippet.
int i;
int j = new int();
//functionally equivalent

Essentially C# interprets both the lines in the same way. Functionally they are equivalent. But there are some added advantage with the object thing that we declare on line 2. We can use the methods that .NET framework provides for the objects.
j.GetType();   //returns System.Int32 the type of the object
j.ToString();  //returns a string
j.Equals(k);   //returns true/false if two objects are equal


This is one way to utilize the power of objects. There's much more. We shall learn about functions in the days to come, but we can discuss a little for the sake of understanding the purpose of objects.
There is a is operator in C#. The is operator returns a boolean type. It returns true if a given object is certain type.
void MyFunction(object obj)
{
 if(obj is int)
 {
  int k = (int)obj;
  //do something with k
 }
 else if(obj is string)
 {
  string s = (string)obj;
  //do something with s
 }
}

The statements on line 5 and 10 are called unboxing process, converting a reference type to its value type. You can see that MyFunction takes an object type as parameter. Then inside the body, you can decide if the object is of certain type. In this case, you just checked if it is an integer or a string type.

The reverse of unboxing is called boxing. Here is an example snippet directly from the MSDN library.
int i = 123;      // a value type 
object o = i;     // boxing 
int j = (int)o;  // unboxing

Constants: Constants are useful constructs in C# and makes your program easier to understand. Lets take an example.
if(i >= 100)
{
 //do something
}

So what is 100? What does that mean? Will it change in future? Surely someone debugging your code in future will ask these questions. This is certainly a bad practice. A general solution to this problem can be
const int HIGH_ORDER = 100;
if(i >= HIGH_ORDER)
{
 //customer asked for more than 100 units
}

The constant makes it clear that some customer asked for atleas 100 units of your goods. Obviously that is a huge order to sell.

Enumerations: Enumerations, or enums, are used to group named constants similar to how they are used in C, C++ or Java. Continuing the above example, if we think of an imaginary inventory store where we keep track of the order of goods that a customer asked for, we can do it in the following way.
public enum GoodsOrder
{
 VeryLow = 10,   //note that each constant ends with a comma ,
 Low = 30,
 Medium = 60,
 High = 100
}

Individually, each of them are constants. But for the sake of our code clarity, we grouped them under an enum and we named it GoodsOrder. So how do we use them? Let's complete the full code.
using System;

namespace Spells
{
    class Program
    {
        public enum GoodsOrder
        {
            VeryLow = 10,   //note that each constant ends with a comma ,
            Low = 30,
            Medium = 60,
            High = 100
        }
        static void Main(string[] args)
        {
            int c_order = 80;   //change the values to see different output

            if (c_order < (int)GoodsOrder.VeryLow)
            {
                Console.WriteLine("Sorry we do not sell below 10 units");
            }
            else if(c_order >= (int)GoodsOrder.VeryLow && c_order < (int)GoodsOrder.Low)
            {
                Console.WriteLine("Each unit will be charged 100 Taka");
            }
            else if (c_order >= (int)GoodsOrder.Low && c_order < (int)GoodsOrder.Medium)
            {
                Console.WriteLine("Each unit will be charged 97 Taka");
                //the customer is taking quite a lot, so you give him a reduced price
            }
            else if (c_order >= (int)GoodsOrder.Medium && c_order < (int)GoodsOrder.High)
            {
                Console.WriteLine("Each unit will be charged 95 Taka");
            }
            else if (c_order >= (int)GoodsOrder.High)
            {
                Console.WriteLine("Each unit will be charged 90 Taka");
                //thats business
            }
            Console.ReadLine();  //this will just keep the console visible
        }
    }
}


Just copy and paste this code and hit F5.

The last thing you need to know, enumerations start by default at 0 and if you do not provide values by yourself, the compiler will assume values starting from 0 and will assign values incrementally to the rest.
public enum GoodsOrder
{
 VeryLow,  //defaults to 0
 Low,   //defaults to 1
 Medium,   //defaults to 2 
 High      //defaults to 3
}

Enumeration is by default integer type. You can assign another type if you think you can optimize the spaces that these constants take in the memory.
public enum GoodsOrder : byte
{
 VeryLow,  //defaults to 0
 Low,   //defaults to 1
 Medium,   //defaults to 2 
 High      //defaults to 3
}

If you declare byte type, make sure that the values range between 0 to 256. You can specify other types like sbyte, short, ushort, int, long, uint, ulong etc.

I hope this post makes good use to your coding experience.