Consider the class of nested arrays, each element can be either an array or a number:
[[1, 2, [3, 4, [5]], [6, 7]], 8]
Here is my attempt to implement the [] operator for it.
class MyArray { List<MyArray> elements; int value; public object this[int index] { get { if (elements.Count > 0) { return elements; } else { return value; } } } }
So the goal is to use it as shown below:
MyArray arr = new MyArray(); ... do something with the array here ... int num = arr[3][5][1];
In the case of access to the "branch" and not the "leaf" (say, arr [3] [5] [1] has several elements), let it simply return 0, infinity or any integer is normal for us.
However, it is obvious that such nested statements will not work for my case, since the result of the statement is an object, not an instance of MyArray.
Currently, I see the only solution: define a conversion operator for int and make the [] operator always return only the element (which will be MyArray, unless we get an exception here). But is there any other way? Maybe using something like an IList interface might help? Or maybe there is a way to define several possible return types for a method in some way? (but so far I googled it is not possible, and there is no type in C #)
source share