Vector start with element greater than 0 (zero)?

Asked

Viewed 192 times

3

Usually a vetor starts from the element 0, and so on until you get to the size of which it was declared or assigned, example:

string[] v = {1, 2 , 3};
// equivalente á:
v[0] = 1;
v[1] = 2;
v[2] = 3;

I want to know how I do in the C# to start the vector already on a predefined element, that is, instead of starting with v[0] begin in v[10] thus:

v[10] = 1;
v[11] = 2;
v[12] = 3;
  • You want all array values (array) to start with a default value, this?

  • Or that the first index is 10? Please put an example of the code you want it to be possible to write...

  • @jbueno not all, only one vector

1 answer

7


In C# I only see a way, create a structure of your own that does this for you. You cannot use anything that already exists directly, array, List, nothing. everything starts from scratch. It may have some structure ready that works differently, but I don’t remember anything standard and I doubt it has in the . NET.

Simplified example of what you can have in your own type:

public class MyList<T> : List<T> {
    public T this[int index] {
        get => base[index - 10];
        set => base[index - 10] = value;
    }
}

I put in the Github for future reference.

I found a response in the OS with a more complete implementation on the one hand, more limited on the other.

I found this response in the OS that gives another solution, but it is very bad to use it.

Another solution that is not ideal: you can simply leave the first 10 elements empty. Make a calculation before using the index. Solve, but not transparently.

I would simply avoid this. Perhaps with a more comprehensive description of the problem, the solution should be another.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.