-2

Im trying to do exactly what the title says

    int[] weeks = {};
    weeks[weeks.Length]=1;

this doesnt work. There is also no .Add Method.

Any ideas? or is this not possible

2
  • What is a "razor array"? Do you mean that you're trying to do this in a view? Commented Apr 30, 2015 at 19:19
  • stackoverflow.com/questions/9570944/… Commented Apr 30, 2015 at 19:21

3 Answers 3

3

Line 1 declares and initializes a new 1-dimensional array of int without specific size. Line 2 resizes the array (weeks) to its actual size, plus 1. Line 3 assigns the value 1 to the element at the last position (that we created in Line 2)

Remember: int[5] weeks; -> to access last element you have to use index 4 -> weeks[4] = 1

int[] weeks = {};
Array.Resize(ref weeks,weeks.Length + 1);
weeks[weeks.Length - 1]=1;
Sign up to request clarification or add additional context in comments.

1 Comment

Would benefit from some explanation.
2

Arrays in C# by definition are of a fixed size, and cannot be dynamically expanded.

I would suggest using a List<>, as they can be dynamically expanded, much like vectors in other programming languages.

List<int> weeks = new List<int>();
weeks.add(1);

See more here.

Comments

1

First of all there is no such thing razor array. Razor is a view engine and array is a data structure. Arrays have fixed length so if you declare an array with the length of 5:

int[] weeks = new int[5];

Trying to add an element to a fifth place will result in IndexOutOfRangeException

If you need some data-structure with variable size you could look at all the objects that implement IList interface for example a List, an ArrayList and others.

IList interface also defines Add method that you requested.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.