Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-0 based arrays in C# with traditional [ ] array syntax?

Tags:

arrays

c#

I'd like to be able to create an array in C# with an arbitrary range of index bounds, e.g., a 16 element array with indices of 100-115.

Native arrays in C# are 0-based, but I'm told (e.g., in Luaan's comment here), that the C# Array class allows arbitrary lower and upper bounds. But in the examples I've seen elements in the Array class are accessed via myArray.GetValue() and myArray.SetValue() instead of conventional array syntax like myArray [ foo ].

Array arr = Array.CreateInstance(typeof(string), new[]{16}, new[]{100});
Console.WriteLine(arr.Length); // 16
arr.SetValue("foo", 100);
Console.WriteLine(arr.GetValue(100)); // foo

Is there any way to make an array with some arbitrary starting index, like [100] that I can access with traditional [ ] syntax in C#?

like image 688
user316117 Avatar asked Sep 11 '26 02:09

user316117


2 Answers

You could create a class that implements the decorator pattern: just implement the IList interface (wich is also implemented by Array) and do whatever shifting you want on the this [int index] property.

The decorator pattern is described here: http://www.codeproject.com/Articles/479635/UnderstandingplusandplusImplementingplusDecoratorp

like image 74
George Lica Avatar answered Sep 13 '26 17:09

George Lica


The Array class does not support this, but you can write your own array class with one-based indices:

public class OneBasedArray<T>
{
    public T[] InnerArray;
    public T this[int i]
    {
        get { return InnerArray[i-1]; }
        set { InnerArray[i-1] = value; }
    }
}

And then use it like this:

var myArray = new OneBasedArray<int> { InnerArray = new int[]{ 1, 2, 3, 4, 5 } };
for(int i = 1; i <=5; i++)
{
    Console.WriteLine(myArray[i]);
}

This code is only to get the idea, such a class would of course need a nicer interface.

like image 30
Lukas Boersma Avatar answered Sep 13 '26 16:09

Lukas Boersma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!