Monday, July 13, 2015

C# Collection Tutorial-Part-5

Queue
The Queue works like FIFO system , a first-in, first-out collection of Objects. Objects stored in a Queue are inserted at one end and removed from the other. The Queue provide additional insertion, extraction, and inspection operations. We can Enqueue (add) items in Queue and we can Dequeue (remove from Queue ) or we can Peek (that is we will get the reference of first item ) item from Queue. Queue accepts null reference as a valid value and allows duplicate elements.
Some important functions in the Queue Class are follows :
  Enqueue : Add an Item in Queue
  Dequeue : Remove the oldest item from Queue
Peek : Get the reference of the oldest item

Enqueue : Add an Item in Queue
  Syntax : Queue.Enqueue(Object)
  Object : The item to add in Queue
days.Enqueue("Sunday");

Dequeue : Remove the oldest item from Queue (we don't get the item later)
  Syntax : Object Queue.Dequeue()
  Returns : Remove the oldest item and return.
days.Dequeue();

Peek : Get the reference of the oldest item (it is not removed permanently)
  Syntax : Object Queue.Peek()
  returns : Get the reference of the oldest item in the Queue
days.peek();

The following CSharp Source code shows some of commonly used functions :
using System;
using System.Collections;
using System.Windows.Forms;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Queue days = new Queue();
            days.Enqueue("Sunday");
            days.Enqueue("Monday");
            days.Enqueue("Tuesday");
            days.Enqueue("Wednsday");
            days.Enqueue("Thursday");
            days.Enqueue("Friday");
            days.Enqueue("Saturday");

            MessageBox.Show (days.Dequeue().ToString ());
            
            if (days.Contains("Monday"))
            {
                MessageBox.Show("The queue contains Monday");
            }
            else
            {
                MessageBox.Show("Does not match any entries");
            }
        }
    }
}

When you execute the above C# source code , you will get Sunday in the messagebox and then it check the Monday is exist in the queue or not. 

C# Collection Tutorial-Part-4

NameValueCollection is used to store a collection of associated String keys and String values that can be accessed either with the key or with the index. It is very similar to C# HashTable, HashTable also stores data in Key , value format .
NameValueCollection can hold multiple string values under a single key. As elements are added to a NameValueCollection, the capacity is automatically increased as required through reallocation. The one important thing is that you have to importSystem.Collections.Specialized Class in your program for using NameValueCollection.
Adding new pairs
  NameValueCollection.Add(name,value)
  NameValueCollection pair = new NameValueCollection();
pair.Add("High", "80");

Get the value of corresponding Key
  string[] NameValueCollection.GetValues(index);
  NameValueCollection pair = new NameValueCollection();
  pair.Add("High", "80");
string[] vals = pair.GetValues(1);

using System;
using System.Collections;
using System.Windows.Forms;
using System.Collections.Specialized;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            NameValueCollection markStatus = new NameValueCollection();
            string[] values = null;

            markStatus.Add("Very High", "80");
            markStatus.Add("High", "60");
            markStatus.Add("medium", "50");
            markStatus.Add("Pass", "40");

            foreach (string key in markStatus.Keys)
            {
                values = markStatus.GetValues(key);
                foreach (string value in values)
                {
                    MessageBox.Show (key + " - " + value);
                }
            } 
        }
    }
}

C# Collection Tutorial-Part-3

Stack 
The Stack class represents a last-in-first-out (LIFO) Stack of Objects. Stack follows the push-pop operations. That is we can Push (insert) Items into Stack and Pop (retrieve) it back . Stack is implemented as a circular buffer. It follows the Last In First Out (LIFO) system. That is we can push the items into a stack and get it in reverse order. Stack returns the last item first. As elements are added to a Stack, the capacity is automatically increased as required through reallocation.
Commonly used methods :
  Push : Add (Push) an item in the Stack data structure
  Pop : Pop return the last Item from the Stack
Contains: Check the object contains in the Stack

Push : Add (Push) an item in the Stack data structure
  Syntax : Stack.Push(Object)
  Object : The item to be inserted.
  Stack days = new Stack();
days.Push("Sunday");

Pop : Pop return the item last Item from the Stack
  Syntax : Object Stack.Pop()
  Object : Return the last object in the Stack
days.Pop();

Contains : Check the object contains in the Stack
  Syntax : Stack.Contains(Object)
  Object : The specified Object to be search
days.Contains("Tuesday");

The following CSharp Source code shows some of important functions in Stack Class:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Stack days = new Stack();
            days.Push("SunDay");
            days.Push("MonDay");
            days.Push("TueDay");
            days.Push("WedDay");
            days.Push("ThuDay");
            days.Push("FriDay");
            days.Push("SaturDay");
            if (days.Count ==7)
            {
                MessageBox.Show(days.Pop().ToString ());
            }
            else
            {
                MessageBox.Show("SaturDay does not exist");
            }
        }
    }
}

When you execute this C# program add seven items in the stack . Then it check the count is equal to 7 , if it is seven then pop() the item. The message box will display SaturDay. 

C# Collection Tutorial-Part-2

HashTable
Hashtable in C# represents a collection of key/value pairs which maps keys to value. Any non-null object can be used as a key but a value can. We can retrieve items from hashTable to provide the key. Both keys and values are Objects.
The commonly used functions in Hashtable are :
  Add  : To add a pair of value in HashTable
  ContainsKey : Check if a specified key exist or not
  ContainsValue : Check the specified Value exist in HashTable
Remove : Remove the specified Key and corresponding Value

Add : To add a pair of value in HashTable
  Syntax : HashTable.Add(Key,Value)
  Key : The Key value
  Value : The value of corresponding key
  Hashtable ht;
ht.Add("1", "Sunday");

ContainsKey : Check if a specified key exist or not
  Synatx : bool HashTable.ContainsKey(key)
  Key  : The Key value for search in HahTable
  Returns : return true if item exist else false
ht.Contains("1");

ContainsValue : Check the specified Value exist in HashTable
  Synatx : bool HashTable.ContainsValue(Value)
  Value : Search the specified Value in HashTable
  Returns : return true if item exist else false
ht.ContainsValue("Sunday")

Remove : Remove the specified Key and corresponding Value
  Syntax : HashTable.Remove(Key)
  Key : The key of the element to remove
ht.Remove("1");

The following source code shows some important operations in a HashTable
using System;
using System.Collections;
using System.Windows.Forms;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Hashtable weeks = new Hashtable();
            weeks.Add("1", "SunDay");
            weeks.Add("2", "MonDay");
            weeks.Add("3", "TueDay");
            weeks.Add("4", "WedDay");
            weeks.Add("5", "ThuDay");
            weeks.Add("6", "FriDay");
            weeks.Add("7", "SatDay");
            //Display a single Item 

            MessageBox.Show(weeks["5"].ToString ());
            //Search an Item 
            if (weeks.ContainsValue("TueDay"))
            {
                MessageBox.Show("Find");
            }
            else
            {
                MessageBox.Show("Not find");
            }
            //remove an Item 
            weeks.Remove("3");
            //Display all key value pairs
            foreach (DictionaryEntry day in weeks )
            {
                MessageBox.Show (day.Key + "   -   " + day.Value );
            }
        }
    }
}

When you execute this C# program it will add seven entries in the hashtable. The first message it will display the item 5. Then it check the value "TueDay" is existing or not . Next it remove the third item from HashTable. Finaly it displays all items exist in the HashTable. 

C# Collection Tutorial-Part-1

CSharp Collections are data structures that holds data in different ways for flexible operations . C# Collection classes are defined as part of the System.Collections or System.Collections.Generic namespace.
Most collection classes implement the same interfaces, and these interfaces may be inherited to create new collection classes that fit more specialized data storage needs. The following tutorial shows how to implement collection classes in C# programming.

ArrayList is one of the most flexible data structure from CSharp Collections. ArrayList contains a simple list of values. ArrayList implements the IList interface using an array and very easily we can add , insert , delete , view etc. It is very flexible because we can add without any size information , that is it will grow dynamically and also shrink .
c-sharp-arraylist
  Add : Add an Item in an ArrayList
  Insert : Insert an Item in a specified position in an ArrayList
  Remove : Remove an Item from ArrayList
  RemoveAt: remove an item from a specified position
Sort : Sort Items in an ArrayList

How to add an Item in an ArrayList ?
  Syntax : ArrayList.add(object)
  object : The Item to be add the ArrayList
  ArrayList arr;
arr.Add("Item1");

How to Insert an Item in an ArrayList ?
  Syntax : ArrayList.insert(index,object)
  index : The position of the item in an ArrayList
  object : The Item to be add the ArrayList
  ArrayList arr;
arr.Insert(3, "Item3");

How to remove an item from arrayList ?
  Syntax : ArrayList.Remove(object)
  object : The Item to be add the ArrayList
arr.Remove("item2")

How to remove an item in a specified position from an ArrayList ?
  Syntax : ArrayList.RemoveAt(index)
  index : the position of an item to remove from an ArrayList
ItemList.RemoveAt(2)

How to sort ArrayList ?
  Syntax : ArrayList.Sort()

The following CSharp source code shows some function in ArrayList

using System;
using System.Collections;
using System.Windows.Forms;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            int i = 0;
            ArrayList ItemList = new ArrayList();
            ItemList.Add("Item4");
            ItemList.Add("Item5");
            ItemList.Add("Item2");
            ItemList.Add("Item1");
            ItemList.Add("Item3");
            MessageBox.Show ("Shows Added Items");
            for (i = 0; i < = ItemList.Count - 1; i++)
            {
                MessageBox.Show(ItemList[i].ToString());
            }
            //insert an item 
            ItemList.Insert(3, "Item6");
            //sort itemms in an arraylist 
            ItemList.Sort();
            //remove an item 
            ItemList.Remove("Item1");
            //remove item from a specified index 
            ItemList.RemoveAt(3);
            MessageBox.Show("Shows final Items the ArrayList");
            for (i = 0; i < = ItemList.Count - 1; i++)
            {
                MessageBox.Show(ItemList[i].ToString());
            }
        }
    }
}
When you execute this C# program , at first add five items in the arraylist and displays. Then again one more item inserted in the third position , and then sort all items. Next it remove the item1 and also remove the item in the third position . Finally it shows the existing items. 

Difference between int, Int16, Int32 and Int64

 In the learning phase developer are not much aware of the difference between primitive, FCL (framework class library), reference, and value types. This cause bugs and performance issues into the code. In this article, I would like to expose the different behavior of integer type.

int

  1. It is a primitive data type defined in C#.
  2. It is mapped to Int32 of FCL type.
  3. It is a value type and represent System.Int32 struct.
  4. It is signed and takes 32 bits.
  5. It has minimum -2147483648 and maximum +2147483647 capacity.

Int16

  1. It is a FCL type.
  2. In C#, short is mapped to Int16.
  3. It is a value type and represent System.Int16 struct.
  4. It is signed and takes 16 bits.
  5. It has minimum -32768 and maximum +32767 capacity.

Int32

  1. It is a FCL type.
  2. In C#, int is mapped to Int32.
  3. It is a value type and represent System.Int32 struct.
  4. It is signed and takes 32 bits.
  5. It has minimum -2147483648 and maximum +2147483647 capacity.

Int64

  1. It is a FCL type.
  2. In C#, long is mapped to Int64.
  3. It is a value type and represent System.Int64 struct.
  4. It is signed and takes 64 bits.
  5. It has minimum –9,223,372,036,854,775,808 and maximum 9,223,372,036,854,775,807 capacity.

Note

  1. A number of developers think that int represents a 32-bit integer when the application is running on a 32-bit OS and it represents a 64-bit integer when the application is running on a 64-bit OS. This is absolutely wrong.
  2. In C# int is a primitive data type and it always mapped to System.Int32 whether the OS is 32-bit or 64-bit.
What do you think?
I hope you will enjoy the tips while programming with C#. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.