Rajesh kumar’s Blog

If you have knowledge, let others light their candles at it.

Posts Tagged ‘Non zero index’

Create non zero indexed arrays in C#

Posted by Rajesh Kumar on December 19, 2011

99.99% of the time, we write our code with zero indexed arrays. However, C# allows us to create non zero based (single or multi dimensional arrays).

The syntax from MSDN is:

public static Array CreateInstance(   
                Type elementType,   
                int[] lengths,
                int[] lowerBounds)

CreateInstance is a static method available in Array class. Here, variable "lengths" indicates the dimension of the array and "lowerBounds" indicates what is the starting lower bound of each dimension array.

To understand the concept in a simple way, let’s consider the single dimension array and the following code is used to create the instance

// Create the instance of an Array   
Array myArray = Array.CreateInstance(typeof(int), new[] { 4 }, new[] { 2011 });
            
// Set the values to array  
myArray.SetValue(5, 2005);   
myArray.SetValue(6, 2006);   
myArray.SetValue(7, 2007);   
myArray.SetValue(8, 2008);   
            
// Display the lower bound of the array  
Console.WriteLine(myArray.GetLowerBound(0));  
            
// Display the upper bound of the array  
Console.WriteLine(myArray.GetUpperBound(0));  
            
// Display all the items in the array  
for (int i = myArray.GetLowerBound(0); i <= myArray.GetUpperBound(0); i++)  
    Console.WriteLine(myArray.GetValue(i));

Pros:

1. More meaningful index, based on scenario.

Cons:

  1. Slow performance.
  2. Non CLS complaint.
Advertisements

Posted in .Net | Tagged: , , | Leave a Comment »