Appendix C. Common Data Types

Each of the .NET languages can provide its own keywords for the types it supports. For example, a keyword for an integer in VB is Integer, whereas in C# or C++ it is int; a boolean is Boolean in VB, but bool in C# or C++. In any case, the integer is mapped to the class Int32, and the boolean is mapped to the class Boolean in the System namespace. Table C-1 lists all simple data types common to the .NET Framework. Non-CLS-compliant types are not guaranteed to interoperate with all CLS-compliant languages.

Table C-1. Common data types

Type

Description

Boolean

True or false.

Byte

8-bit unsigned integer: 0 to 255.

Char

Character. Unicode 16-bit character.

DateTime

Represents a date and time value.

Decimal

Can represent positive and negative values with 28 significant digits: -79,228,162,514,264,337,593,543,950,335 to 79,228,162,514,264,337,593,543,950,335 .

Double

Stores 64-bit floating-point values: -1.79769313486231570e308 to 1.79769313486231570e308.

Guid

Represents a globally unique identifier (GUID); this is stored internally as a 128-bit integer. Commonly represented as a series of lowercase hexadecimal digits in groups of 8, 4, 4, 4, and 12 digits and separated by hyphens (e.g., 382c74c3-721d-4f34-80e5-57657b6cbc27).

Int16

Stores 16-bit signed integers: -32,768 to 32,767.

Int32

Stores 32-bit signed integers: -2,147,483,648 to 2,147,483,647.

Int64

Stores 64-bit signed integers: -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.

SByte

Represents an 8-bit signed integer. The SByte type is not CLS-compliant. -128 to 127.

Single

Represents an IEEE 754f, single precision, 32-bit value: -3.40282346638528859e38 to 3.40282346638528859e38.

String

Represents a string of Unicode characters.

UInt16

Represents a 16-bit unsigned integer. The UInt16 type is not CLS- compliant. 0 to 65,535.

UInt32

Represents a 32-bit unsigned integer. The UInt32 type is not CLS- compliant. 0 to 4,294,967,295

UInt64

Represents a 64-bit unsigned integer. The UInt64 type is not CLS- compliant. The UInt64 data type can represent positive integers with 18 significant digits: 0 to 184,467,440,737,095,551,615.

Void

Void.

Table C-2 shows a number of useful container types that the .NET Framework provides.

Table C-2. Container types

Type

Description

Array

General array construct.

ArrayList

This class implements the IList interface. The array can grow or shrink dynamically in size.

BitArray

This class represents a compact array of bit values. Each element represents a Boolean value (true/false).

HashTable

This class represents a collection of associated keys and values that are organized based on the hash code of the key.

Queue

This class represents a first-in, first-out collection construct.

SortedList

This class is similar to HashTable except that all elements are sorted by their actual keys (not hashed) and elements are accessible through either key or index.

Stack

This class represents a first-in, last-out stack construct.

Usage

This section demonstrates how you can take advantage of container types. We don’t illustrate all methods and properties, but we show the important characteristics of these types. All examples in this chapter are in C#; however, you can use these CLS types from any other CLS-compliant languages.

Array

Array, by definition, stores homogeneous information in a structure that allows for indexing, enumerating, and so on. It is very important in the daily programmer’s life. In the following code listing, we demonstrate some of the syntax for using Array. In C#:

using System;
public class TestArray {

   public static void Main(  )  {

      string[] strArray = new string[7] { "Monday", "Tuesday", "Wednesday", 
"Thursday", "Friday", "Saturday", "Sunday" };
      for(int i=0; i<strArray.Length; i++) {
         Console.WriteLine(String.Format("item at {0} is {1}",
                                         i, strArray[i]));
      }

      int[] iArray;
      iArray = new int[7];

      for(int i=0; i<iArray.Length; i++) {
         iArray[i] = i;
      }
      for(int i=0; i<iArray.Length; i++) {
         Console.WriteLine(iArray[i]);
      }

   }
}

and in VB:

Imports System
Public Class TestArray

   Public Shared Sub Main(  )

      Dim i as Integer
      Dim strArray(  ) as String = { "Monday", "Tuesday", "Wednesday", 
"Thursday", "Friday", "Saturday", "Sunday" }

      For i = 0 To strArray.Length - 1
         Console.WriteLine(String.Format("item at {0} is {1}", _
                                         i, strArray(i)))
      Next

      Dim iArray(6) as Integer

      For i = 0 To iArray.Length - 1
         iArray(i) = i
      Next
      For i = 0 to iArray.Length - 1
         Console.WriteLine(iArray(i))
      Next

   End Sub
End Class

Notice the differences in the declaration of the array for the highlighted code. In VB, the number represents the upper bound of the array, not the size.

ArrayList

In the following code listing, we demonstrate some of the critical usages of the ArrayList class, such as adding data to the end of the list, inserting data anywhere in the list, iterating through the list, and sorting the list:

using System;
using System.Collections;
public class TestArrayList {

   public static void Main(  )  {

      ArrayList arrList = new ArrayList(  );
      arrList.Add("Monday");
      arrList.Add("Tuesday");
      arrList.Add("Wednesday");
      arrList.Add("Thursday");

      // We'll try to insert Friday afterward.
      // arrList.Add("Friday");

      arrList.Add("Saturday");
      arrList.Add("Sunday");

      int i = 0;
      IEnumerator arrIterator = arrList.GetEnumerator(  );
      Console.WriteLine("There are: {0} days in a week.", arrList.Count);
      while(arrIterator.MoveNext(  )) {
         Console.WriteLine("[{0}] {1}", i++, arrIterator.Current);
      }

      Console.WriteLine("Insert Friday");
      arrList.Insert(4, "Friday");

      i = 0;
      arrIterator = arrList.GetEnumerator(  );
      Console.WriteLine("There are: {0} days in a week.", arrList.Count);
      while(arrIterator.MoveNext(  )) {
         Console.WriteLine("[{0}] {1}", i++, arrIterator.Current);
      }

      arrList.Sort(  );

      i = 0;
      arrIterator = arrList.GetEnumerator(  );
      Console.WriteLine("Sorted as text");
      while(arrIterator.MoveNext(  )) {
         Console.WriteLine("[{0}] {1}", i++, arrIterator.Current);
      }

      Object oDay = "Friday";
      Console.WriteLine("Index for Friday using BinarySearch: {0}", 
                        arrList.BinarySearch(oDay));
      Console.WriteLine("Index for Sunday using BinarySearch: {0}", 
                        arrList.BinarySearch("Sunday"));
   }
}

BitArray

The sample code for BitArray is self-explanatory, as shown in the following code listing. We use the bit array to store and retrieve access rights in the following example. You can use the Set and Get methods as well as the [] operator:

using System;
using System.Collections;
public class TestBitArray  {

   enum Permissions {canRead, canWrite, canCreate, canDestroy};      

   public static void Main(  )  {
   
      BitArray bitArr = new BitArray(4);
      bitArr.Set((int)Permissions.canRead, true);
      bitArr[(int)Permissions.canWrite] = false;
      bitArr[(int)Permissions.canCreate] = true;
      bitArr[(int)Permissions.canDestroy] = false;

      Console.WriteLine("bitArr count: {0}	length: {1}", 
                        bitArr.Count, 
                        bitArr.Length);

      Console.WriteLine("Permissions:");
      Console.WriteLine("Read: {0}", 
                        bitArr[(int)Permissions.canRead]);
      Console.WriteLine("Write: {0}", 
                        bitArr[(int)Permissions.canWrite]);
      Console.WriteLine("Create: {0}", 
                         bitArr[(int)Permissions.canCreate]);
      Console.WriteLine("Destroy: {0}", 
                         bitArr[(int)Permissions.canDestroy]);
   }
}

HashTable

The HashTable data type is similar to the dictionary object, which is basically an associated array. Each element stored in the table is associated with a key. Because HashTable implements the IDictionaryEnumerator, we can obtain the enumerator to help us iterate through the data collection. As you can see from the sample code, we can also loop through the data using the keys or values collection:

using System;
using System.Collections;
public class TestHashtable  {

   public static void Main(  )  {

      Hashtable hashTbl = new Hashtable(  );
      hashTbl.Add("Param1", "UserName");
      hashTbl.Add("Param2", "Password");

      IDictionaryEnumerator hashEnumerator = hashTbl.GetEnumerator(  );
      Console.WriteLine(  );
      Console.WriteLine("Loop through with enumerator:");
      while (hashEnumerator.MoveNext(  )) {
         Console.WriteLine("Key: {0}	Value: {1}", 
                           hashEnumerator.Key, 
                           hashEnumerator.Value);
      }

      Console.WriteLine(  );
      Console.WriteLine("Loop through Keys:");
      foreach(string key in hashTbl.Keys) {
         Console.WriteLine(key); 
      }

      Console.WriteLine(  );
      Console.WriteLine("Loop through Values:");
      foreach(string val in hashTbl.Values) {
         Console.WriteLine(val); 
      }

      Console.WriteLine(  );
      Console.WriteLine("Loop through Keys:");
      foreach(string key in hashTbl.Keys) {
         Console.WriteLine("Key: {0}	Value: {1}", key, hashTbl[key]);
      }
   }
}

Queue

To demonstrate the use of a queue Abstract Data Type (ADT), we created a fictitious order-processing code listing. Each enqueued item represents a line item in a typical order. We will then dequeue each line item and perform the total calculation:

using System;
using System.Collections;

public class TestQueue  {

   public static void Main(  )  {
      string sLineItem1, sLineItem2;
      Queue myQueue = new Queue(  );

      sLineItem1 = "123	Item 123	4	3.39";
      sLineItem2 = "ABC	Item ABC	1	9.49";
      myQueue.Enqueue(sLineItem1);
      myQueue.Enqueue(sLineItem2);

      Console.WriteLine("
Processing Order:
");
      String sLineItem = "";
      String [] lineItemArr;
      Decimal total = 0;
      while(myQueue.Count > 0) {
         sLineItem = (String)myQueue.Dequeue(  ); 
         Console.WriteLine( "	{0}", sLineItem);
         lineItemArr = sLineItem.Split(new Char[] {'	'});
         total += Convert.ToInt16(lineItemArr[2]) *
                 Convert.ToDecimal(lineItemArr[3]);
      }
      Console.WriteLine("
Order Total: {0}
", total);
   }
}

SortedList

The following code demonstrates the sorted list ADT. A sorted list is similar to a hash table or a dictionary type. Each item of data is associated with the key with which the list is sorted. Notice that the strings are added to the list in no particular order. However, when we iterate through the list, all strings are sorted by their associated keys:

using System;
using System.Collections;
public class TestSortedList  {

   public static void Main(  )  {

      SortedList mySortedList = new SortedList(  );
      mySortedList.Add("AA", "Hello");
      mySortedList.Add("AC", "!");
      mySortedList.Add("AB", "World");

      Console.WriteLine("
Loop through manually:
");
      for(int i=0; i< mySortedList.Count; i++) {
         Console.WriteLine("Key: {0}	Value: {1}", 
                           mySortedList.GetKey(i), 
                           mySortedList.GetByIndex(i));
      }

      IDictionaryEnumerator myIterator = mySortedList.GetEnumerator(  );
      Console.WriteLine("
Loop through with enumerator:
");
      while (myIterator.MoveNext(  )) {
         Console.WriteLine("Key: {0}	Value: {1}", 
                           myIterator.Key, 
                           myIterator.Value);
      }
   }
}

Stack

The following code demonstrates the first-in, last-out characteristics of the stack abstract data type. The output from the pop operation initially shows the fourth item, the third item, and so on:

using System;
using System.Collections;
public class TestStack{

   public static void Main(  )  {

      Stack myStack = new Stack(  );
      myStack.Push("Item 1");
      myStack.Push("Item 2");
      myStack.Push("Item 3");
      myStack.Push("Item 4");

      while(myStack.Count > 0) {
         Console.WriteLine(myStack.Pop(  ));
      }
   }
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.86.134