How can I start the index in an ArrayList
at 1 instead of 0? Is there a way to do that directly in code?
(Note that I am asking for ArrayList
, for plain arrays please see Initializing an array on arbitrary starting index in c#)
Java arrays are always 0-based. You can't change that behavior. You can fill or use it from another index, but you can't change the base index. It's defined in JLS §10.4, if you are interested in it.
The ArrayList index starts at 0 just like arrays, but instead of using the square brackets [] to access elements, you use the get(index) to get the value at the index and set(index,value) to set the element at an index to a new value.
Explanation: No. You can not change the C Basic rules of Zero Starting Index of an Array.
ArrayList get index of element If the object is present then return value will be greater than '-1 '. Note – Please note that arraylist index starts from 0.
One legitimate reason to do this is in writing unit tests. Certain 3rd party SDKs (for example Excel COM interop) expect you to work with arrays that have one-based indices. If you're working with such an SDK, you can and should stub out this functionality in your C# test framework.
The following should work:
object[,] comInteropArray = Array.CreateInstance(
typeof(object),
new int[] { 3, 5 },
new int[] { 1, 1 }) as object[,];
System.Diagnostics.Debug.Assert(
1 == comInteropArray.GetLowerBound(0),
"Does it look like a COM interop array?");
System.Diagnostics.Debug.Assert(
1 == comInteropArray.GetLowerBound(1),
"Does it still look like a COM interop array?");
I don't know if it's possible to cast this as a standard C# style array. Probably not. I also don't know of clean way to hard-code the initial values of such an array, other than looping to copy them from a standard C# array with hard-coded initial values. Neither of these shortcomings should be a big deal in test code.
Here is something I am using right now to quickly port a VBA application to C#:
It's an Array class that starts with 1 and accepts multiple dimensions.
Although there is some additional work to do (IEnumerator, etc...), it's a start, and is enough to me as I only use indexers.
public class OneBasedArray<T>
{
Array innerArray;
public OneBasedArray(params int[] lengths)
{
innerArray = Array.CreateInstance(typeof(T), lengths, Enumerable.Repeat<int>(1, lengths.Length).ToArray());
}
public T this[params int[] i]
{
get
{
return (T)innerArray.GetValue(i);
}
set
{
innerArray.SetValue(value, i);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With