Professional Documents
Culture Documents
Week 7: C#Zone
Week 7: C#Zone
Introduction
Arrays in C# are one of the most used objects. In this article, you will learn the basics of arrays
and how to use arrays in C#.
In C#, an array index starts at zero. That means the first item of an array starts at the
0th position. The position of the last item on an array will total number of items - 1. So if an
array has 10 items, the last 10th item is at 9th position.
Let's take a look at simple declarations of arrays in C#. The following code snippet defines the
simplest dynamic array of integer types that does not have a fixed size.
int[] intArray;
As you can see from the above code snippet, the declaration of an array starts with a type of
array followed by a square bracket ([ ]) and name of the array.
The following code snippet declares an array that can store 5 items only starting from index 0
to 4.
1. int[] intArray;
2. intArray = new int[5];
The following code snippet declares an array that can store 100 items starting from index 0 to 99.
1. int[] intArray;
2. intArray = new int[100];
Initializing Arrays
Once an array is declared, the next step is to initialize an array. The initialization
process of an array includes adding actual data to the array.
The following code snippet creates an array of 3 items and values of these items are
added when the array is initialized .
1. // Initialize a fixed array
2. int[] staticIntArray = new int[3] {1, 3, 5};
Alternative, we can also add array items one at a time as listed in the following code
snippet.
1. // Initialize a fixed array one item at a time
2. int[] staticIntArray = new int[3];
3. staticIntArray[0] = 1;
4. staticIntArray[1] = 3;
5. staticIntArray[2] = 5;
The following code snippet declares a dynamic array with string values.
1. // Initialize a dynamic array items during declaration
2. string[] strArray = new string[] { "Saqib", "Numan", "Talha", "Azeem", "Qaiser" };
Accessing Arrays
We can access an array item by passing the item index in the array. The following
code snippet creates an array of three items and displays those items on the
console.
1. // Initialize a fixed array one item at a time
2. int[] staticIntArray = new int[3];
3. staticIntArray[0] = 1;
4. staticIntArray[1] = 3;
5. staticIntArray[2] = 5;
6. // Read array items one by one
7. Console.WriteLine(staticIntArray[0]);
8. Console.WriteLine(staticIntArray[1]);
9. Console.WriteLine(staticIntArray[2]);
This method is useful when you know what item you want to access from an array. If you try to
pass an item index greater than the items in array, you will get an error.
The foreach control statement (loop) is used to iterate through the items of an array.
For example, the following code uses foreach loop to read all items of an array of
strings.
1. // Initialize a dynamic array items during declaration
2. string[] strArray = new string[] {
3. "Saqib",
4. "Numan",
5. "Talha ",
6. "Azeem",
7. "Qaiser"
8. };
9. // Read array items using foreach loop
10. foreach(string str in strArray) {
11. Console.WriteLine(str);
12. }
This approach is used when you do not know the exact index of an item in an array and needs
to loop through all the items.
Types of Array
Arrays can be divided into the following four categories.
Single-dimensional arrays
Multidimensional arrays or rectangular arrays
Jagged arrays
Mixed arrays.
The following code declares an integer array that can store 3 items. As you can see
from the code, first I declare the array using [] bracket and after that I instantiate the
array by calling the new operator.
int[] intArray;
intArray = new int[3];
Array declarations in C# are pretty simple. You put array items in curly braces ({}). If
an array is not initialized, its items are automatically initialized to the default initial
value for the array type if the array is not initialized at the time it is declared.
The following code declares and initializes an array of three items of integer type.
int[] staticIntArray = new int[3] {1, 3, 5};
You can even directly assign these values without using the new operator.
string[] strArray = { "Saqib", "Numan", "Talha", "Azeem", "Qaiser" };
Multi-Dimensional Arrays
A multi-dimensional array, also known as a rectangular array is an array with more than
one dimension. The form of a multi-dimensional array is a matrix.
Declaring a multi-dimensional array
A multi dimension array is declared as following:
string[,] mutliDimStringArray;
A multi-dimensional array can be fixed-sized or dynamic sized.
Now let's see examples of multi-dimensional dynamic arrays where you are not sure of
the number of items of the array. The following code snippet creates two multi-
dimensional arrays with no limit.
You can also omit the new operator as we did in single dimension arrays. You can assign these values
directly without using the new operator. For example:
1. int[, ] numbers = {
2. {
3. 1,
4. 2
5. },
6. {
7. 3,
8. 4
9. },
10. {
11. 5,
12. 6
13. }
14. };
15. string[, ] names = {
16. {
17. "Numan",
18. "Saqib"
19. },
20. {
21. "Kinza",
22. "Pakiza"
23. }
24. };
We can also initialize the array items one item at a time. The following code snippet is an example of
initializing array items one at a time.
Jagged Arrays
Jagged arrays are arrays of arrays. The elements of a jagged array are other arrays.
Declaring Jagged Arrays
Declaration of a jagged array involves two brackets. For example, the following code
snippet declares a jagged array that has three items of an array.
int[][] intJaggedArray = new int[3][ ];
The following code snippet declares a jagged array that has two items of an array.
string[][] stringJaggedArray = new string[2][]
We can also initialize a jagged array's items by providing the values of the array's items.
The following code snippet initializes item an array's items directly during the
declaration.
Complete Example
1. Console.WriteLine("Single Dimension Array Sample");
2. // Single dim array
3. string[] strArray = new string[] ] {
4. "Saqib",
5. "Numan",
6. "Talha",
7. "Azeem",
8. "Qaiser"
9. };
10. // Read array items using foreach loop
11. foreach(string str in strArray) {
12. Console.WriteLine(str);
13. }
14. Console.WriteLine("-----------------------------
-----------------------------");
15. Console.WriteLine("Multi-Dimension
Dimension Array Sample");
16. string[, ] string2DArray = new string[2, 2] {
17. {
18. "Saqib",
19. "Numan"
20. }, {
21. "Kinza",
22. "Pakiza"
23. }
24. };
25. foreach(string str in string2DArray) {
26. Console.WriteLine(str);
27. }
28. Console.WriteLine("-----------------------------
-----------------------------");
29. Console.WriteLine("Jagged Array Sample");
30. int[][] intJaggedArray3 = {
31. new int[] {
32. 2,
33. 12
34. },
35. new int[] {
36. 14,
37. 14,
38. 24,
39. 34
40. },
41. new int[] {
42. 6,
43. 16,
44. 26,
45. 36,
46. 46,
47. 56
48. }
49. };
50. // Loop through all itesm of a jagged array
51. for (int i = 0; i < intJaggedArray3.Length; i++) {
52. Console.Write("Element({0}):
"Element({0}): ", i);
53. for (int j = 0; j < intJaggedArray3[i].Length; j++) {
54. Console.Write("{0}{1}", intJaggedArray3[i][j], j == (intJaggedArray3[i].Length -
1) ? "" : " ");
55. }
56. Console.WriteLine();
57. }
58. Console.WriteLine("-----------------------------
--------------------------");
Ref: C#Corner Pick “N” Share :C#Notes
ArrayList
Introduction
ArrayList implements the IList interface using an array whose size is dynamically
increased as required. In this article I explain how to create the ArrayList and the
various methods and properties of the ArrayList.
Creation of ArrayList
The datatype of an ArrayList is object type, so we can add the elements having the datatype string,
integer and any other.
The following code describes how we add the elements to the ArratList.
namespace ArrayList1
{
class Program
{
static void Main(string[] args)
{
ArrayList arr = new ArrayList();
();
arr.Add("Sunday");
arr.Add("Monday");
arr.Add("Tuesday");
arr.Add("Wednesday");
arr.Add("Thusday");
arr.Add("Friday");
arr.Add("Saturday");
Console.WriteLine("The
"The elements of the ArrayList are:");
are:"
foreach (object obj in arr)
{
Console.WriteLine(obj);
}
}
}
}
Ref: C#Corner Pick “N” Share :C#Notes
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
ArrayList arr = new ArrayList();
arr.Add("Sunday");
arr.Add("Monday");
arr.Add("Tuesday");
arr.Add("Wednesday");
Console.WriteLine("*******Properties*********");
Console.WriteLine("Capacity of Elements {0}" , arr.Capacity);
arr.Add("Thusday");
arr.Add("Friday");
arr.Add("Saturday");
Console.WriteLine("Capacity of Elements NOW {0}", arr.Capacity);
Console.WriteLine("Total Number of Elements in List {0}", arr.Count);
Console.WriteLine("The elements of the ArrayList are:");
foreach (object obj in arr)
{
Console.WriteLine(obj);
}
Console.WriteLine("*******Methods*********");
arr.Clear(); //to clear ArrayList
Console.WriteLine("After Clear Number of Elements in List {0}", arr.Count);
arr.Insert(0,"Saqib"); //to insert elements in the ArrayList
arr.Insert(1, "Numan");
arr.Insert(2, "Azeem");
Console.WriteLine(arr);
foreach (object obj in arr)
{
Console.WriteLine(obj);
}
Console.WriteLine("*******After Remove*******");
arr.Remove( "Saqib"); // to remove element
foreach (object obj in arr)
{
Console.WriteLine(obj);
}
}
}
}
Hashtable
A Hashtable is a collection that stores (Keys, Values) pairs. Here, the Keys are used to find the storage
location and is immutable and cannot have duplicate entries in the Hashtable. The .Net Framework has
provided a Hash Table class that contains all the functionality required to implement a hash table without
any additional development. The hash table is a general-purpose dictionary collection. Each item within the
collection is a DictionaryEntry object with two properties: a key object and a value object. These are
known as Key/Value. When items are added to a hash table, a hash code is generated automatically. This
code is hidden from the developer. All access to the table's values is achieved using the key object for
identification. As the items in the collection are sorted according to the hidden hash code, the items should
be considered to be randomly ordered.
Declaring a Hashtable
The Hashtable class is generally found in the namespace called System.Collections. So to execute any of the
examples, we have to add using System.Collections; to the source code.The declaration for the Hashtable is:
Hashtable HT = new Hashtable();
This new Hashtable has the limited capacity and when the limit is reached then the capacity is automatically
increased to allow for further storage. Since the nature of the Hashtable dictionary is that the capacity is always
considered to be approximate we can set the initial approximate capacity by passing the integer parameteger to the
constructor as:
Hashtable HT = new Hashtable(100);
This is useful when the maximum size of the collection is known because it removes the need of resizing the hash
table and also it increases the performance.
Properties of Hashtable
Some of the important properties of a hash table are:
Comparer: Gets or Sets the IComparer to use for the Hash Table.
Count: Gets the number of key/value pairs contained in the hash table.
Item: Gets or Sets the value associated with the specified Key.
Methods of Hashtable
Some of the important methods of a hash table are:
Add: Adds an element with the specified key and value in the hash table.
ContainsKey: Determined whether the hash table contains a specified key or not.
ContainsValue: Determined whether the hash table contains a specified value or not.
Example
static void Main(string[] args)
{
Hashtable HT = new Hashtable
Hashtable();
HT.Add(1, "N");
HT.Add(2, "U");
HT.Add(3, "M");
HT.Add(4, "A");
HT.Add(5, "N");
List
The List(of T) class in .NET represents a strongly typed list of objects that can be accessed by
index. List class is a collection and defined in the System.Collections.Generic namespace and
hence
ence provides most of the collections related built
built-in
in methods and properties including add,
remove, search, and sort.
The Remove method is used to delete an item from the List. The Clear method can be used to
clear all items from the list. The Contains method can be used to find an item.
The following code sample shows how to add items to a List. The code also uses Remove,
Clear, and Contains methods to delete and find items.
Ref: C#Corner Pick “N” Share :C#Notes
Example
static void Main(string[] args)
{
List<string> authors = new List<string>();
Console.WriteLine("\nCapacity: {0}", authors.Capacity);
authors.Add("Numan Ashraf");
authors.Add("Saqib Sajjad");
authors.Add("Muhammad Azeem");
authors.Add("Qaiser Farooq");
authors.Add("Muhammad Talha");
Console.WriteLine();
foreach (string author in authors)
{
Console.WriteLine(author);
}
Console.WriteLine("Number of Authors in List: {0}", authors.Count);
Console.WriteLine("\nContains(\"Author\"): {0}",
authors.Contains("Muhammad Azeem"));
Console.WriteLine("\nInsert(2, \"Pakiza\")");
authors.Insert(2, "Pakiza");
Console.WriteLine();
foreach (string author in authors)
{
Console.WriteLine(author);
}
Console.WriteLine("\nauthors[3]: {0}", authors[3]);
Console.WriteLine("\nRemove(\"Numan Ashraf\")");
authors.Remove("Numan Ashraf");
Console.WriteLine();
foreach (string author in authors)
{
Console.WriteLine(author);
}
Console.WriteLine();
authors.Sort();
Console.WriteLine("Sorted List");
foreach (string author in authors)
{
Console.WriteLine(author);
}
authors.TrimExcess();
Console.WriteLine("\nTrimExcess()");
Console.WriteLine("Capacity: {0}", authors.Capacity);
Console.WriteLine("Count: {0}", authors.Count);
authors.Clear();
Console.WriteLine("\nClear()");
Console.WriteLine("Capacity: {0}", authors.Capacity);
Console.WriteLine("Count: {0}", authors.Count);
Console.ReadKey();
}
Stack
It represents a last-in, first out collection of object. It is used when you need a last-
in, first-out access of items. When you add an item in the list, it is called pushing the
item and when you remove it, it is called popping the item.
1 Count
The following table lists some of the commonly used methods of the Stack class −
Returns the object at the top of the Stack without removing it.
Example
The following example demonstrates use of Stack −
using System;
using System.Collections;
namespace CollectionsApplication {
class Program {
st.Push('A');
st.Push('M');
st.Push('G');
st.Push('W');
st.Push('V');
st.Push('H');
Console.WriteLine("The next poppable value in stack: {0}", st.Peek());
Console.WriteLine("Current stack: ");
foreach (char c in st) {
Console.Write(c + " ");
}
Console.WriteLine();
When the above code is compiled and executed, it produces the following result −
Current stack:
W G M A
The next poppable value in stack: H
Current stack:
H V W G M A
Removing values
Current stack:
G M A
Queue
It represents a first-in, first out collection of object. It is used when you need a first-
in, first-out access of items. When you add an item in the list, it is called enqueue,
and when you remove an item, it is called deque.
1 Count
The following table lists some of the commonly used methods of the Queue class −
Example
The following example demonstrates use of Stack −
using System;
using System.Collections;
namespace CollectionsApplication {
class Program {
q.Enqueue('A');
q.Enqueue('M');
q.Enqueue('G');
q.Enqueue('W');
Console.WriteLine();
q.Enqueue('V');
q.Enqueue('H');
Console.WriteLine("Current queue: ");
foreach (char c in q) Console.Write(c + " ");
Console.WriteLine();
Console.WriteLine("Removing some values ");
char ch = (char)q.Dequeue();
Console.WriteLine("The removed value: {0}", ch);
ch = (char)q.Dequeue();
Console.WriteLine("The removed value: {0}", ch);
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result −
Current queue:
A M G W
Current queue:
A M G W V H
Removing values
The removed value: A
The removed value: M