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 2 other followers

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: