Shiman’s Weblog

Collecting stones from the sea-shore.

C# .NET Collections (The Stack)

Stack collections are abstract Last In First Out (LIFO) data structures, that is, the last inserted item is the first item to be removed. A Stack has a default capacity of 32 if not mentioned.

The following table lists the member of the Stack collection.

Stack Members

Member Name

Syntax

Clear

This method removes all the elements of the collection.

virtual void Clear()

Contains

This method returns true if the specified value is found in the collection. If the value is not found, false is returned.

virtual bool Contains(object value)

Peek

The Peek method previews the last element on the stack. The element is returned without removal from the stack.

virtual object Peek()

Pop

This method returns and removes the top element of the stack.

virtual object Pop()

Push

This method pushes another element on the stack.

virtual void Push(object obj)

Synchronized

This method returns a thread-safe wrapper for the Stack collection.

static Stack Synchronized(

    Stack sourceStack)

ToArray

This method returns the Stack collection as a regular array.

virtual object[] ToArray()

 

Here is a sample code to demonstrate the Stack collection.

using System;
using System.Collections;
using System.Text;
 
namespace Examples.Collections
{
    class StackCollection
    {
        public static void Main()
        {
            Stack stack = new Stack();
            stack.Push(2);
            stack.Push(4);
            stack.Push(6);
 
            Console.WriteLine("Total items in the stack : {0}", stack.Count);
 
            Console.WriteLine("The top item in the stack : {0}", stack.Peek());
 
            Console.WriteLine("Performing Pop() :");
            while (stack.Count != 0)
            {
                Console.WriteLine("\t" + stack.Pop());
            }
 
            Console.ReadKey();
        }
    }
}

 

 

June 30, 2008 Posted by shiman | C#.Net, Computer Science, OOP, Programming | , , , , | No Comments Yet

C# .NET Collections (The SortedList)

The SortedList collection is a combination of key/value entries and an ArrayList collection, where the collection is sorted by the key. A SortedList element can be accessed by its key, like an element in any IDictionary implementation, or by its index, like an element in any IList implementation. A SortedList object internally maintains two arrays to store the elements of the list; that is, one array for the keys and another array for the associated values.

The table includes the members of the SortedList collection.

SortedList Members

Member Name

Syntax

Constructor

The SortedList constructor is overloaded. These are some of the overloaded constructors.

SortedList()

SortedList(IComparer comparer)

SortedList(
    IDictionary sourceCollection)

Add

This method adds an element to the collection.

virtual void Add(object key,
    object value)

Capacity

This property gets or sets the capacity of the collection.

virtual int Capacity{
    get; set;}

Clear

This method removes all the elements of the collection.

virtual void Clear()

Contains

This method returns true if the specified value is found in the collection. If the value is not found, false is returned.

virtual bool Contains(object value)

ContainsKey

This method returns true if the key is found in the collection. If the key is not present, false is returned. Identical to the Contains method.

virtual bool ContainsKey(
    object key)

ContainsValue

This method returns true if the value is found in the collection. If the value is not present, false is returned.

virtual bool ContainsValue(
    object value)

GetByIndex

This method returns the value at the index.

virtual object GetByIndex(
    int index)

GetKey

This method returns the key at the specified index.

virtual object GetKey(
    int index)

GetKeyList

This method returns all the keys in the collection.

virtual IList GetKeyList()

GetValueList

This method returns all the values of the SortedList in a new collection.

virtual IList GetValueList()

IndexOfKey

This method returns the index of a key found in the collection.

virtual int IndexOfKey(
    object key)

IndexOfValue

This method returns the index to the first instance of this value in the collection.

virtual int IndexOfValue(
    object value)

IsFixedSize

This property returns true if the collection is fixed size. Otherwise, false is returned.

virtual bool IsFixedSize{
    get;}

IsReadOnly

This property returns true if the collection is read-only. Otherwise, false is returned.

virtual bool IsReadOnly{
    get;}

Item

This property gets or sets the value of this key.

virtual object this[object key]
    {get; set;}

Keys

This property returns the keys of the SortedList collection.

public virtual ICollection Keys{
    get;}

Remove

This method removes an element, which is identified by the key, from the collection.

virtual void Remove(
    object key)

RemoveAt

This method removes an element at the specific index.

virtual void RemoveAt(
    int index)

SetByIndex

This method set the value of the element at the specified index.

virtual void SetByIndex(
    int index, object value)

Synchronized

This method returns a thread-safe wrapper for a queue object.

static SortedList Synchronized(
    SortedList sourceList)

TrimToSize

This method trims the capacity to the actual number of elements in the collection.

virtual void TrimToSize()

Values

This property returns the values of the collection.

virtual ICollection Values{
    get;}

IEnumerable members

GetEnumerator

ICloneable members

Clone

ICollection members

CopyTo, Count, IsSynchronized, and SyncRoot

The following code illustrates the SortedList collection a bit.

using System;
using System.Collections;

namespace Examples.Collections
{
    class SortedListCollection
    {
        public static void Main()
        {

            // create a SortedList object
            SortedList mySortedList = new SortedList();

            // add elements containing US state abbreviations and state
            // names to mySortedList using the Add() method
            mySortedList.Add("NY", "New York");
            mySortedList.Add("FL", "Florida");
            mySortedList.Add("AL", "Alabama");
            mySortedList.Add("WY", "Wyoming");
            mySortedList.Add("CA", "California");

            // get the state name value for "CA"
            string myState = (string)mySortedList["CA"];
            Console.WriteLine("myState = " + myState);

            // get the state name value at index 3 using the GetByIndex() method
            string anotherState = (string)mySortedList.GetByIndex(3);
            Console.WriteLine("anotherState = " + anotherState);

            // display the keys for mySortedList using the Keys property
            foreach (string myKey in mySortedList.Keys)
            {
                Console.WriteLine("myKey = " + myKey);
            }

            // display the values for mySortedList using the Values property
            foreach (string myValue in mySortedList.Values)
            {
                Console.WriteLine("myValue = " + myValue);
            }

            Console.ReadKey();

        }
    }
}

 

June 28, 2008 Posted by shiman | C#.Net, Computer Science, OOP, Programming | , , , , | 2 Comments

C# .NET Collections(The Queue)

Queue is a Simple DataStucture which allows Insert/Remove of Items at one of the ends only. It is basically called as FIFO (First In First Out) data structure, i.e. The item which is added first is the first one to be removed. .NET has a built in class for Queue. It is found in the System.Collections namespace. The initial capacity is 32 elements. Queue collections are ideal for messaging components.

Table: Queue Members

Member Name

Syntax

Constructor

public Queue()

public Queue(

ICollection sourceCollection)

 

public Queue(int capacity)

 

public Queue(int capacity,

float factor)

Clear

This method removes all the elements of the collection.

virtual void Clear()

Contains

This method returns true if the specified value is found in the collection. If the value is not found, false is returned.

virtual bool Contains(object value)

Dequeue

This method removes and returns the first element of the queue.

virtual object Dequeue()

Enqueue

This method adds an element to the queue.

virtual void Enqueue(

object element)

Peek

This method returns the first element of the queue without removing it.

virtual object Peek()

Synchronized

This method returns a thread-safe wrapper for a queue object.

static Queue Synchronized(

Queue sourceQueue)

ToArray

This method creates a new array initialized with the elements of the queue.

virtual object[] ToArray()

TrimToSize

This method sets the capacity to the number of elements in the collection.

virtual void TrimToSize()

IEnumerable members

GetEnumerator

ICloneable members

Clone

ICollection members

CopyTo, Count, IsSynchronized, and SyncRoot

This is sample code of the Queue collection.

 

 

using System;
using System.Collections;
using System.Text;
using System.Xml;
namespace Examples.Collections
{
    class QueueCollection
    {
 
        static void Main()
        {
            Queue queue = new Queue();
            queue.Enqueue(2);
            queue.Enqueue(4);
            queue.Enqueue(6);
 
            Console.WriteLine("The element of the queue are :");
            while (queue.Count != 0)
            {
                Console.WriteLine("\t{0}", queue.Dequeue());
            }
 
            queue.Clear();
            Console.WriteLine("Elements after Clear(): {0}", queue.Count);
 
            queue.Enqueue(2);
            queue.Enqueue(4);
            queue.Enqueue(6);
 
            if (queue.Contains(6))
            {
                Console.WriteLine("The Queue contains 6");
            }
 
            Console.WriteLine("The first element of the queue is : {0}", queue.Peek());
 
            object[] oArray;
 
            oArray = queue.ToArray();
 
            Console.WriteLine("The elements of the array are :");
            foreach (object o in oArray)
            {
                Console.WriteLine("\t{0}", o);
            }
 
            Console.ReadKey();
        }
    }
}

 

June 23, 2008 Posted by shiman | C#.Net, Computer Science, OOP, Programming | , , , , | No Comments Yet

C# .NET Collections (The Hashtable)

A hash table is a data structure used to store a set of values that can each be identified by a unique key.  The key can then be used as a lookup to find any individual item in the set.  However, rather than storing the unique key value directly, the key is hashed.  The hashing process converts the key data into an index number and the value data linked to the key is placed in a storage location defined by that index.

The main advantage of the hash table structure is the ability to rapidly locate items, even in very large sets of data.  If the key value of a desired data value is known, the key can be hashed and the value’s location found directly.  There is no requirement to iterate through the entire data set to find an item or to sort the set in order to perform a binary search. Example:

Table: Hashtable Members

Member Name

Syntax

Constructor

The Hashtable constructor is overloaded. These syntaxes are some of the overloaded constructors.

Hashtable()

Hashtable(int capacity)

 

Hashtable(int capacity,

    float loadFactor)

Add

This method adds an element to the collection.

virtual void Add(object key,

    object value)

Contains

This method returns true if the key is found in the collection. If the key is not present, false is returned.

virtual bool Contains(

    object key)

ContainsKey

This method returns true if the key is found in the collection. If the key is not present, false is returned. Identical to the Contains method.

virtual bool ContainsKey(

    object key)

ContainsValue

This method returns true if the value is found in the collection. If the value is not present, false is returned.

virtual bool ContainsValue(

    object value)

EqualityComparer

IEqualityComparer EqualityComparer {

    get;}.

GetHash

This method returns the hash code for the specified key.

virtual int GetHash(

    object key)

GetObjectData

This is the method implemented to serialize the collection.

virtual void GetObjectData(

    SerializationInfo info,

    StreamingContext context)

IsFixedSize

This property returns true if the collection is fixed size. Otherwise, false is returned.

virtual bool IsFixedSize{

    get;}

IsReadOnly

This property returns true if the collection is read-only. Otherwise, false is returned.

virtual bool IsReadOnly{

    get;}

IsSynchronized

This property returns true if the collection is synchronized.

virtual bool IsSynchronized{

    get;}

Item

This property gets or sets a value related to a key.

virtual object this[object key]{

    get; set;}

KeyEquals

This method compares a key to a value. If equal, true is returned. Otherwise, false is returned. This method is primarily used to compare two keys.

virtual bool KeyEquals(

    object item,

    object key)

Keys

Returns a collection that contains the keys of the Hashtable.

virtual ICollection Keys{

    get;}

OnDeserialization

This method is called when deserialization is completed.

virtual void OnDeserialization(

    object sender)

Remove

This method removes an element with the specified key from the collection.

virtual void Remove(

    object key)

Synchronized

This method returns a thread-safe wrapper of the collection.

static Hashtable Synchronized(

    Hashtable sourceTable)

Values

Returns a collection that has the values of the Hashtable.

virtual ICollection values{

    get;}

IEnumerable members

GetEnumerator

ICloneable members

Clone

ICollection members

CopyTo, Count, IsSynchronized, and SyncRoot

 

using System;

using System.Collections;

 

namespace Examples.HashTable

{

    public class Starter

    {

        public static void Main()

        {

            Hashtable employees = new Hashtable();

            employees.Add(“A100″, new Employee(“Ben”, true, false, true));

            employees.Add(“V100″, new Employee(“Valerie”, false, false, true));

            Participation((Employee)employees["A100"]);

            Participation((Employee)employees["V100"]);

        }

 

        public static void Participation(Employee person)

        {

            Console.WriteLine(person.Name + “:”);

            if (person.InProfitSharing)

            {

                Console.WriteLine(” Participating in” + ” Profit Sharing”);

            }

            if (person.InHealthPlan)

            {

                Console.WriteLine(” Participating in” + ” Health Plan”);

            }

            if (person.InCreditUnion)

            {

                Console.WriteLine(” Participating in” + ” Credit Union”);

            }

        }

    }

 

    public class Employee

    {

 

        public Employee(string emplName)

        {

            propName = emplName;

            eflags.SetAll(true);

        }

 

        public Employee(string emplName,

                        bool profitSharing,

                        bool healthPlan,

                        bool creditUnion)

        {

            propName = emplName;

            InProfitSharing = profitSharing;

            InHealthPlan = healthPlan;

 

            InCreditUnion = creditUnion;

        }

 

        private BitArray eflags = new BitArray(3);

 

        public bool InProfitSharing

        {

            set

            {

                eflags.Set(0, value);

            }

            get

            {

                return eflags.Get(0);

            }

        }

 

        public bool InHealthPlan

        {

            set

            {

                eflags.Set(1, value);

            }

            get

            {

                return eflags.Get(1);

            }

        }

 

        public bool InCreditUnion

        {

            set

            {

                eflags.Set(2, value);

            }

            get

            {

                return eflags.Get(2);

            }

        }

 

        private string propName;

        public string Name

        {

            get

            {

                return propName;

            }

        }

    }

}

 

Hashtable.GetEnumerator implements IDictionary.GetEnumerator, which returns an IDictionary Enumeator. IDictionaryEnumerator implements the IEnumerator interface. It also adds three properties: Entry, Key, and Value. This is sample code of the IDictionaryEnumerator enumerator:

using System;

using System.Collections;

 

namespace Example.HashTable

{

    public class Program

    {

        public static void Main()

        {

            Hashtable zHash = new Hashtable();

            zHash.Add(“one”, 1);

            zHash.Add(“two”, 2);

            zHash.Add(“three”, 3);

            zHash.Add(“four”, 4);

            IDictionaryEnumerator e =

 

                zHash.GetEnumerator();

            while (e.MoveNext())

            {

                Console.WriteLine(“{0} {1}”, e.Key, e.Value);

            }

        }

    }

}

 

June 19, 2008 Posted by shiman | C#.Net, Computer Science, OOP, Programming | , , , , | No Comments Yet

C# .NET Collections (The BitArray)

The BitArray class manages a compact array of bit values. The values of the array are represented as booleans, where true indicates that the bit is on one (1), and false indicates that the bit is on zero (0).

Table : BitArray Members

Member Name

Syntax

Constructor

The BitArray constructor is overloaded. These are some of the overloaded constructors.

BitArray(bool [] bits)

BitArray(int [] bits)

BitArray(int count,

bool default)

And

This method performs a bitwise And on the current and BitArray parameter. The result is placed in the returned BitArray.

BitArray And(BitArray value)

Get

This method returns a specific bit in the BitArray collection.

bool Get(int index)

IsReadOnly

This property returns true if the collection is read-only. Otherwise, the property returns false.

virtual bool IsReadOnly{

get;}

Item

This property gets or sets the bit at the index.

virtual object this[int index] {

get;set;}

Length

This property gets or sets the number of bits in the collection.

public int Length{

get; set; }

Not

This method negates the bits of the BitArray collection. The result is placed in the returned BitArray.

BitArray Not()

Or

This method performs a bitwise Or on the current and BitArray parameter. The result is placed in the returned BitArray.

BitArray Or(BitArray value)

Set

This method sets a specific bit in the collection.

Void Set(int index, bool value)

SetAll

This method sets all the bits of the collection to true or false.

void SetAll(bool value)

Xor

This method performs an exclusive OR on the current collection and the BitArray parameter.

BitArray Xor(

BitArray value)

IEnumerable members

GetEnumerator

ICloneable members

Clone

ICollection members

CopyTo, Count , IsSynchronized , and SyncRoot

The following code is a simple example of the BitArray collection.

using System;
using System.Collections;
class MainClass
{
    public static void DisplayBitArray(string arrayListName, BitArray myBitArray )
    {
        for (int i = 0; i < myBitArray.Count; i++)
        {
            Console.WriteLine(arrayListName + "[" + i + "] = " + myBitArray[i]);
        }
    }
    public static void Main()
    {
        BitArray myBitArray = new BitArray(4);
        myBitArray[0] = false;
        myBitArray[1] = true;
        myBitArray[2] = true;
        myBitArray[3] = false;
        DisplayBitArray("myBitArray", myBitArray);

        BitArray anotherBitArray = new BitArray(myBitArray);
        DisplayBitArray("anotherBitArray", myBitArray);

    }
}

June 14, 2008 Posted by shiman | C#.Net, Computer Science, OOP, Programming | , , , , | No Comments Yet

Collections in C# .NET (The ArrayList)

An array list is a dynamic array. Although indigenous arrays are static, elements can be added or removed from an ArrayList at run time. Elements of the ArrayList are not automatically sorted. Similar to single-dimensional arrays, the elements of an ArrayList are accessible using the indexing operator and indices.

In addition to the standard collection interfaces, ArrayList implements the IList interface. The following Table lists the ArrayList-specific methods and properties. The static members of ArrayList are thread-safe, whereas instance members are not. The common collection interfaces—ICollection, IEnumerable, and ICloneable—are not discussed in detail.The following code uses various ArrayList methods and properties. It creates a new ArrayList, which is then initialized with command-line parameters. The Add method is called to add elements to the ArrayList. The ArrayList is then sorted and cloned. Then the values at the elements of the cloned ArrayList are doubled. Afterward, the cloned ArrayList is enumerated and every element is displayed.

Table: ArrayList Members

Member Name

Syntax

Constructors

ArrayList()

ArrayList(

ICollection sourceCollection)

ArrayList(int capacity)

Adapter

This method creates a wrapper for an IList collection.

static ArrayList Adapter(

IList list)

Add

This method adds an element to the end of the ArrayList collection.

virtual int Add(object value)

AddRange

This method adds a range of elements to the ArrayList collection. The elements are input from an ICollection type, such as a regular array.

virtual void AddRange(

ICollection elements)

BinarySearch

This method performs a binary search for a specific value in a sorted array.

virtual int BinarySearch(

object value)

virtual int BinarySearch(

object value,

IComparer comparer)

virtual int BinarySearch(

int index,

int count,

object value,

IComparer comparer)

Capacity

This property gets or sets the number of properties allowed in the collection. The default capacity is 16 elements. Capacity is different from the number of elements. The capacity is automatically increased as elements are added. When the number of elements exceeds the current capacity, the capacity doubles. Capacity is for better memory management of elements in the collection.

virtual int Capacity {

get; set}

Clear

This method removes all the elements of the collection.

virtual void Clear()

Contains

This method returns true if the specified item is found in a collection. If the item is not found, false is returned.

virtual bool Contains(object item)

Count

This property returns the number of elements in the collection.

virtual int Count{

get; }

FixedSize

This method creates a wrapper for an ArrayList or IList collection, in which elements cannot be added or removed.

static ArrayList FixedSize(

ArrayList sourceArray)

static IList FixedSize(

IList sourceList)

GetRange

This method returns a span of elements from the current array. The result is stored in a destination ArrayList.

virtual ArrayList GetRange(

int index, int count)

IndexOf

This method returns the index of the first matching element in the collection.

virtual int IndexOf(

object value)

virtual int IndexOf(object value,

int startIndex)

virtual int IndexOf(object value,

int startIndex,

int count)

Insert

This method inserts an element into the collection at the specified index.

virtual void Insert(int index,

object value)

InsertRange

This method inserts multiple elements into the collection at the specified index.

virtual void InsertRange(

int index,

ICollection sourceCollection)

IsFixedSize

This property returns true if the collection is fixed-length. Otherwise, the property returns false.

virtual bool IsFixedSize{

get;}

IsReadOnly

This property returns true if the collection is read-only. Otherwise, the property returns false.

virtual bool IsReadOnly{

get;}

Item

This property gets or sets the element at the index.

virtual object this[int index] {

get;set;}

LastIndexOf

This method returns the index of the last matching element in the collection.

virtual int LastIndex(

object value)

virtual int LastIndexOf(object value,

int startIndex)

virtual int LastIndexOf(object value,

int startIndex,

int count)

ReadOnly

This method creates a read-only wrapper for an IList object.

static ArrayList ReadOnly(

ArrayList sourceArray)

static IList ReadOnly(

IList sourceList)

Remove

This method removes the first element in the collection that matches the value.

virtual void Remove(

object value)

RemoveAt

This method removes the element at the index from the collection.

virtual void RemoveAt(

int index)

RemoveRange

This method removes a range of elements from a collection.

virtual void RemoveRange(

int index,

int count)

Repeat

This method returns an ArrayList with each element initialized to the same value. Count is the number of times to replicate the value.

static ArrayList Repeat(

object value,

int count)

Reverse

This method reverses the order of elements in the collection.

virtual void Reverse()

virtual void Reverse(

int beginIndex,

int endingIndex)

SetRange

This method copies elements from a collection into the same elements in the ArrayList collection.

virtual void SetRange(

int index,

ICollection sourceCollection)

Sort

This method sorts an ArrayList.

virtual void Sort()

virtual void Sort(

IComparer comparer}

virtual void Sort(int index,

int count,

IComparer comparer)

Synchronized

This method returns a thread-safe wrapper of an ArrayList or IList object.

static ArrayList Synchronized(

ArrayList sourceArray)

static IList Synchronized(

IList sourceList)

ToArray

This method copies elements from the current array into a new collection.

virtual object [] ToArray()

virtual Array ToArray(Type type)

TrimToSize

This method sets the capacity to the number of elements in the collection.

virtual void TrimToSize()

IEnumerable members

GetEnumerator

ICloneable members

Clone

ICollection members

CopyTo, Count, IsSynchronized, and SyncRoot

 

using System;
using System.Collections;
namespace Examples.Collection
{
public class Starter
{
public static void Main(string [] argv)
{
ArrayList al1=new ArrayList();
foreach(string arg in argv)
{
al1.Add(int.Parse(arg));
}
al1.Sort();
ArrayList al2=(ArrayList)al1.Clone();
for(int count=0;count<al2.Count;++count)
{
al2[count]=((int)al2[count])*2;
}
foreach(int number in al2)
{
Console.WriteLine(number); 
}
}
}
}

June 9, 2008 Posted by shiman | C#.Net, Computer Science, OOP, Programming | , , , , | 3 Comments

Jagged Array in C# .NET

Jagged arrays are often called array of arrays. More specifically, a jagged array is an array of vectors. Unlike rectangular arrays, a jagged array, as the name implies, is jagged as each vector in the array can be of different length. With jagged arrays, first define the number of rows or vectors in the jagged array. Second, declare the number of elements in each row.

The syntax for declaring a jagged array is similar to a multidimensional array. Instead of a single bracket ([r,c]), jagged arrays have two brackets ([r][]). When declaring a jagged array, the number of columns is not specified and is omitted. The number of elements in each row is set individually.

These are the syntaxes of jagged arrays:

  1. type [][] arrayname;
  2. type [][] arrayname = new type[r][];
  3. type [][] arrayname = new type[r][] {ilist};
  4. type[][] arrayname = new type[][] {ilist};
  5. type[][] arrayname = {ilist};

This is sample code for declaring a jagged array:

int[][] zArray;                        // syntax 1
int[][] yArray = new int[3][];         // syntax 2
int[][] xArray = new int[3][]{         // syntax 3
new int [] {1,2,3},
new int[] {1,2},
new int[] {1,2,3,4}};
int[][] wArray = new int[][]{         // syntax 4
                  new int [] {1,2,3},
                  new int[] {1,2},
                  new int[] {1,2,3,4}};
int[][] wArray = {                    // syntax 5
                  new int [] {1,2,3},
                  new int[] {1,2},
                  new int[] {1,2,3,4}};

The rows of the jagged array are initialized to one-dimensional arrays. Because the rows are assigned distinct arrays, the length of each row may vary. Therefore, a jagged array is essentially an array of vectors:

jarray[row]=new type[elements];

Here is sample code that employs a jagged array:

static void Main(string[] args)
{
...
// A jagged MD array (i.e., an array of arrays).
// Here we have an array of 5 different arrays.
int[][] myJagArray = new int[5][];
// Create the jagged array.
for (int i = 0; i < myJagArray.Length; i++)
myJagArray[i] = new int[i + 7];
// Print each row (remember, each element is defaulted to zero!)
for(int i = 0; i < 5; i++)
{
Console.Write("Length of row {0} is {1} :\t", i, myJagArray[i].Length);
for(int j = 0; j < myJagArray[i].Length; j++)
Console.Write(myJagArray[i][j] + " ");
Console.WriteLine();
}
}

June 8, 2008 Posted by shiman | C#.Net, Computer Science, OOP, Programming | , , , , | 3 Comments

A Very Practical Example of Boxing and Unboxing in C# .NET

Boxing and Unboxing – these two techniques are two of the most commonly used techniques in software development in a team. It is quite obvious that one developer is developing a class or method that is dependent on classes or methods being developed by other developers not knowing anything about their code base and vice versa. So, how will you pass a parameters to their method or what will they return to your call? Boxing and Unboxing are the two techniques to answer this question.

The term Boxing refers to an implicit casting and the term Unboxing refers to explicit casting. Let’s look at them:

//Boxing
int i = 5;
object o = i; // Implicit Casting 
//Unboxing
int j = (int)o; //Explicit Casting

Assume that you are working on a project with a team of three developers. According to your design, you need to develop three classes – MyPoint, My3DPoint and MyPrinter The responsibilities and the developers of the classes are:

  • MyPoint – Define a 2D point – Developer1.
  • My3DPoint – Define a 3D point – Developer2.
  • MyPrinter – Print the information of the other two classes – You.

The basic idea that everyone knows, is this: Developer1 and Developer2 will define their objects and pass to the PrintInfo() method of MyPrinter class to print their information. So, the codes of Developer1 and Developer2 will be something like this:

//Developer1
namespace Points
{
public class MyPoint
{
public int x;
public int y;           
}
 
public class Starter
{
public static void Main(string[] args)
{
MyPoint p = new MyPoint();
p.x = 4;
p.y = 5;
Utility.PrintInfo(p);
}
}
}

//Developer2
namespace Points
{
public class My3DPoint
{
public int x;
public int y;           
public int z;
}
 
public class Starter
{
public static void Main(string[] args)
{
MyPoint p = new MyPoint();
p.x = 4;
p.y = 5;
p.z = 5; 
Utility.PrintInfo(p);
}
}
}

Now, what will you do? Of course, you have a way towards method overloading. But, what if there are hundreds of types you have to deal with? Is it possible to make hundreds of overloads? So, here comes the Boxing and Unboxing to rescue developers like you. Simply, write your code like this:

namespace Printer
{
public class MyPrinter
{
public void PrintInfo(Object o) //Boxing is done here
{
if(o is MyPoint)
{
MyPoint p = new MyPoint();
p = (MyPoint)o; // Unboxing
Console.Writeline(“The point is ({0}, {1})”, p.x, p.y);
}
else if(o is My3DPoint)
{
My3DPoint p = new My3DPoint();
p = (My3DPoint)o; // Unboxing
Console.Writeline(“The point is ({0}, {1}, {2})”, p.x, p.y, p.z);
} 
}
}
}

Pretty easy, isn’t it?

June 5, 2008 Posted by shiman | C#.Net, Computer Science, OOP, Programming, S/W Engineering | , , , , | 2 Comments

Identity VS Equivalence : Reference Type VS Value Type in C# .NET

Reference and value types support different memory models. References refer to objects created on the managed heap, whereas value types are created on the stack. Equivalence and identity complement the memory model. Equivalence is the value or state of an instance. Related instances that have the same value are equivalent. Identity is the location of an object.

Equivalent values are related types that contain the same value. In the following code, integers localA and localC are equivalent. However, the variables are not identical because they are stored at different locations on the stack. The variables localA and localB are neither equivalent nor identical. They have different values and are stored at different locations on the stack:

int localA = 5;
int localB = 10;
int localC = 5;

Assigning a value type copies the value. The target and source are equivalent after this assignment, but not identical:

localA = localB; // localA and localB are equivalent.

For reference types, there is synchronicity of equivalence and identity. Related references containing the same value are equivalent and identical. Assigning a reference creates an alias, which can create unplanned side effects. For this reason, be careful when assigning references. The following code has some unplanned side effects:

using System;
namespace Examples.IdentityVsEquivalence 
{
public class XInt 
{
public int iField=0;
}
public class Starter
{
public static void Main()
{
XInt obj1=new XInt();
obj1.iField=5;
XInt obj2=new XInt();
obj2.iField=10;
// Alias created and second instance lost
obj2=obj1;
obj1.iField=15; // side effect
Console.WriteLine("{0}", obj2.iField); // 15
}
}
}

June 4, 2008 Posted by shiman | C#.Net, Computer Science, OOP, Programming | , , , , | No Comments Yet

The Basics of Structures in C# .NET

Structures are lightweight classes. Similar to classes, structures have behaviors and attributes. As a value type, structures directly contain their value and are stored on the stack. Because structures reside on the stack, keep them small. Do not cache large objects on the stack. The implementation of structures in C# enforces the policy of using a structure as a lightweight class. The following list details the differences between structures and classes:

  • Structures are sealed and cannot be inherited.
  • Structures cannot inherit classes and other structures.
  • Structure implicitly inherits from System.ValueType.
  • The default constructor of a structure cannot be replaced by a custom constructor.
  • Custom constructors of a structure must fully initialize the value of the structure.
  • Structures do not have destructors.
  • Field initialization is not allowed. Const members of a structure can be initialized.

Structure syntax:

attributes accessibility struct structname: interfacelist { structbody };

There are several attributes that target structures. Structures support the same accessibility of a class. Structures implicitly inherit System.ValueType and cannot explicitly inherit another type. However, structures can implement interfaces. Interfacelist is a list of interfaces the structure implements. The structbody encompasses the member functions and data members of the structure.

The default constructor of a structure initializes each field to a default value. You cannot replace the default constructor of a structure. Unlike a class, adding custom constructors to a structure does not remove the default constructor. Invoke a custom constructor with the new operator. The new operator will not place the structure on the managed heap. It is a call to the parameterized constructor of a structure. Structures are commonly declared without the new operator. In that circumstance, the default constructor is called.

Fraction is a structure that models naturally a fraction. Fraction has two double members. It is small and ideal for a structure.

using System;
namespace Examples.Structures
{
public struct Fraction 
{
public Fraction(double _divisor, double _dividend) 
{
divisor=_divisor;
dividend=_dividend;
}
public double quotient 
{
get 
{
return divisor/dividend;
}
}
private double divisor;
private double dividend;
}
public class Calculate 
{
public static void Main()
{
Fraction number=new Fraction(4,5);
Console.WriteLine("{0}", number.quotient);
}
}
}

June 4, 2008 Posted by shiman | C#.Net, Computer Science, OOP, Programming | , , , , | No Comments Yet