Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do I change array indexation?

Status
Not open for further replies.

kindanew

Programmer
Jan 21, 2006
2
SE
Hi
When I make an array it allways starts indexing from 0.
How do I make it start on 1 instead in C#?
I want my array to go from 1 to 5 instead of 0 to 4

Sorry if this is a stupid question but I can't seem to find this anywhere.
Thanks!
 
C# arrays always start at 0. The language spec says:
MSDN said:
array-creation-expression:
new non-array-type [ expression-list ] rank-specifiersopt array-initializeropt
new array-type array-initializer
where the expression-list specifics how many elements in each dimension, not their starting & ending indices.

However, you can use the System.Array.CreateInstance() method to create a System.Array (not the same as a C# array, but sometimes convertible to/from one) that starts somewhere other than 0. It's method signature is:
MSDN said:
public static Array CreateInstance(
Type elementType,
int[] lengths,
int[] lowerBounds
);
Here's how to use it.
Code:
int[] lenArray = new int[5];
int[] boundsArray = new int[1];
System.Array a = System.Array.CreateInstance(typeof(int), lenArray, boundsArray);

Console.WriteLine("Lower:" + a.GetLowerBound(0).ToString() + " Upper:" + a.GetUpperBound(0).ToString());
Chip H.

____________________________________________________________________
If you want to get the best response to a question, please read FAQ222-2244 first
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top