Application security

Collection

Ajay Yadav
February 26, 2013 by
Ajay Yadav

Objective of the Module:

  • Introduction
  • ArrayList
  • Hashtable
  • BitArray

Introduction

.NET offers a variety of collections such as ArrayLists, hashtables, queues, and dictionaries and these collections are abstractions of data algorithms. The ArrayList abstract is a dynamic array, the hashtable collection abstract is a lookup table, the queues collection abstract queues, and so on. In addition, collections implement the ICollection,IEnumerable and IClonable interface. The detailed specification for each collection is found under the System.Collection namespace.

ArraysList Collection

ArrayList is a dynamic array which implements the IList interface. Each element is accessible using the indexing operator. While the traditional array has a fixed number of elements, ArrayList elements can be added or removed at run time.

We can an object from the ArrayList by using a general type of syntax, as shown below:

ArrayList obj = new ArrayList();

Here, you can use the new keyword to create an instance of the ArrayList object. You don't need to specify the size. Once you have an empty ArrayList object, you can use the Add() method to add elements to it.

obj.Add("item1");

obj.Add("2");

obj.Add("Delhi");

Each new item in the ArrayList is added to the end of the list, so it has largest index number. If you wanted to add an item in the middle of the list, you can use Insert () with a numeric argument, as shown below:

Obj.Insert(2,"item2");

You can also remove members of the ArrayList using either Remove() or RemoveAt() methods, as seen below:

Obj.Remove("item1");

Obj.RemoveAt(3);

Benefits of ArrayLists

  • Insert Elements: An ArrayList starts with a collection containing no elements. You can add them in any position as you choose them.
  • Automatic Resizing: You do not need to specify the array size. As you add elements, the array automatically ensures there is enough array.
  • Flexibility when Removing elements: You can remove any elements from Arraylist very easily.

Limitations of ArrayLists

The flexibility of ArrayList comes at a cost of performance. Since memory allocation is a very expensive business, the fixed number of elements of the simple array makes it a lot faster to work with.

Note: ArrayLists are slower and more resource-intensive compared to a conventional Array.

Simple ArrayList Example

The following example showcases an array list with an undefined size. Elements are adding dynamically, as per the requirement. We are adding elements via the Add() method as well as using the Insert() method at a specific location. Later, we are displaying all the elements by iterating the 'for' loop.

using System;

using System.Collections;

namespace CollectionApp

{

classProgram

{

staticvoid Main(string[] args)

{

//Defining an ArrayList

ArrayList obj = newArrayList();

//Adding elements

obj.Add("India");

obj.Add("USA");

obj.Add("Russia");

obj.Add("300");

//Adding elements to specific position

obj.Insert(2, "Japan");

//Accessing elements

for (int i = 0; i < obj.Count;i++ )

{

Console.WriteLine("At Index["+i+"]= "+obj[i].ToString());

}

Console.WriteLine("_________________");

Console.WriteLine("Press any key");

Console.ReadKey();

}

}

}

After the build-up and running of this program, the output of the following program will be something like this:

Figure 1.1 – Array List

Hashtables

In some respect, Hashtable objects are quite similar to an ArrayList object, except that it is not required to use a numerical index. Instead, we can use a texture key that can be numeric.

You can create a Hashtable object by using the same syntax as an ArrayList:

Hashtable obj = new Hashtable();

Once it is created, you have to specify the key/value pairs. Remember that the key is like an index for the entry and the value is the data we are storing. We store each elements using the Add() method with the following syntax:

Obj["in"] = "india";

Obj["en"] = "England";

Obj["us"] = "USA";

Hashtables with numbers or dates for the keys are written as follows:

Obj[Convert.ToDateTime("21/12/2012")] = "The Judgment day";

Note: You need to convert the DateTime index values when they are used as an index for a Hashtable.

To read elements, you just need to specify that the key and value is returned. The following code puts the value "india" into a variable named Country:

string Country = Convert.ToString(obj["in"]);

Benefits of Hashtable

  • Insert elements: You can add as many pairs of key/value elements as required; you don't have to specify the size ahead of time.
  • Non-numeric index: You can use text, numbers and dates as your key (index).
  • Faster lookup: The hashtable collection caters very fast lookup of elements.
  • Flexibility when removing elements: You can remove any elements from ArrayList very easily.

Limitations of Hashtable

  • Key must be unique: The Hashtable stipulates the key uniqueness requirement which is very cumbersome to manipulate.
  • No useful sorting: The sorting is not done by using key or values. The items in the Hashtable are sorted internally to make it easy to find objects very quickly.
  • Performance: Although the lookup is very quick in the Hashtable, CLR has to do quite a lot of work in order to keep its mechanism, which is very resource intensive.

Simple Hashtable Example

The following Hashtable program manipulates with date index. First, we define a Hashtable object and add some predefined dates monuments in the object. Thereafter, we create a DateTime type variable to store user inputs and finally, we display the output.

using System;

using System.Collections;

namespace CollectionApp

{

classProgram

{

staticvoid Main(string[] args)

{

//Defining an Hashtable

Hashtable obj = newHashtable();

//Adding elements

obj[Convert.ToDateTime("02/14/2012")] = "Valentine day";

obj[Convert.ToDateTime("12/22/2012")] = "Math day";

obj[Convert.ToDateTime("08/15/1947")] = "Independence day";

//input date from user

Console.WriteLine("Enter date 'Month/Date/Year' Format");

DateTimeDateData = DateTime.Parse(Console.ReadLine());

//display data

Console.WriteLine(obj[DateData]);

Console.WriteLine("_________________");

Console.WriteLine("Press any key");

Console.ReadKey();

}

}

}

After successfully compiling the aforementioned program, the output will be as follows:

Figure 1.2 - Hashtable

BitArray

Bit values are 1 and 0, where 1 represents true and 0 is false. BitArray collections provides an efficient means of storing and retrieving bit values. It allows us to perform bitwise operations as well as count the total number of bits. The content of this collection is not Objects but rather Boolean values because BitArray can hold a large number of Boolean values, which are called bits. One of most significant features of the BitArray is the fact that it's resizable, which is useful if you don't know the number of bits needed in advance.

You can create a BitArray object by using the same syntax as defined to the other collections. BitArray provides several constructors. Here we are defining 7 bits length in the BitArray:

BitArray obj = new BitArray(7);

Note: The static members of BitArray are threaded-safe whereas instance members are not.

Simple BitArray Example

The following program demonstrates BitArray manipulation. It creates a bit array with 16 bits, indexed from 0 to 15. The Count Property calculates the total number of bits. The SetAll() method sets all the 16 bits to true. Then the Set() method changes the third bit to false. Instead of the Set method, you can also use an indexer.

using System;

using System.Collections;

namespace CollectionApp

{

classProgram

{

staticvoid Main(string[] args)

{

// BitArray definition

BitArray bobj = newBitArray(16);

// calaculate total bits

Console.WriteLine("Total bits="+bobj.Count);

//set all bits to 1

bobj.SetAll(true);

//set 2nd bit to false

bobj.Set(2, false);

//set bit using Indexer

bobj[3] = false;

DislayBits(bobj);

Console.WriteLine("n_________________");

Console.WriteLine("Press any key");

Console.ReadKey();

}

staticvoid DislayBits(BitArray obj)

{

foreach(bool bits in obj)

{

if (bits)

Console.Write(1); // Console.Write(bit ? 1 : 0);

else

Console.Write(0);

}

}

}

}

This is the displayed results of the initialized and configured bits:

Figure 1.3 – Bit Array

11 courses, 8+ hours of training

11 courses, 8+ hours of training

Learn cybersecurity from Ted Harrington, the #1 best-selling author of "Hackable: How to Do Application Security Right."

The BitArray collection implements the properties and methods of the ICollection interface. The following table shows the properties and method of BitArray.

Members Descriptions

Properties Count Contains the number of items currently in the bitarray

IsReadOnly Contains True if the bitarray is read-only and False otherwise

IsSynchronized Contains True if the bitarray is synchronized and False otherwise

Item[] Contains an index of all the items in the bitarray

Length Enables the developer to get and change the length of the bitarray

Methods And() Performs the logical 'And' operation on the bitarray

Clone() Returns a copy of the bitarray

CopyTo() Copies the bitarray to another type of collection

Get() Returns the value of a specific location in the bitarray

Not() Performs the logical 'Not' operation on the bitarray

Or() Performs the logical 'Or' operation on the bitarray

Set() Sets the value of a specific location in the bitarray

SetAll() Sets all the values in the bitarray
Ajay Yadav
Ajay Yadav

Ajay Yadav is an author, Cyber Security Specialist, SME, Software Engineer, and System Programmer with more than eight years of work experience. He earned a Master and Bachelor Degree in Computer Science, along with abundant premier professional certifications. For several years, he has been researching Reverse Engineering, Secure Source Coding, Advance Software Debugging, Vulnerability Assessment, System Programming and Exploit Development.

He is a regular contributor to programming journal and assistance developer community with blogs, research articles, tutorials, training material and books on sophisticated technology. His spare time activity includes tourism, movies and meditation. He can be reached at om.ajay007[at]gmail[dot]com