-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

Guillermo Gutiérrez
  • 17,273
  • 17
  • 89
  • 116
mwild
  • 1,483
  • 7
  • 21
  • 41

3 Answers3

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;
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.

Ellis
  • 173
  • 13
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.

Alex Art.
  • 8,711
  • 3
  • 29
  • 47