Rajesh kumar’s Blog

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

  • Author

  • Rajesh Tweets

    Error: Twitter did not respond. Please wait a few minutes and refresh this page.

  • Enter your email address to follow this blog and receive notifications of new posts by email.

    Join 3 other followers

Archive for December, 2011

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  
// Display the upper bound of the array  
// Display all the items in the array  
for (int i = myArray.GetLowerBound(0); i <= myArray.GetUpperBound(0); i++)  


1. More meaningful index, based on scenario.


  1. Slow performance.
  2. Non CLS complaint.

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