94

I've just started learning C# and in the introduction to arrays they showed how to establish a variable as an array but is seems that one must specify the length of the array at assignment, so what if I don't know the length of the array?

UnkwnTech
  • 88,102
  • 65
  • 184
  • 229

11 Answers11

124

Arrays must be assigned a length. To allow for any number of elements, use the List class.

For example:

List<int> myInts = new List<int>();
myInts.Add(5);
myInts.Add(10);
myInts.Add(11);
myInts.Count // = 3
Hutch
  • 987
  • 10
  • 19
Samuel
  • 37,778
  • 11
  • 85
  • 87
  • 3
    `List myInts = new List();` could work. – string.Empty Oct 09 '13 at 07:57
  • 2
    If arrays Must be assigned a length, then why can I do this: String[] arr = "test;the;values;now".Split(';'); and it just determines the length? And yet I cannot take that same line of code, and move the variable declaration to another line. – matthew_360 Feb 10 '15 at 20:03
  • @matthew_360 Inside the split function, the array is actually being called with a fixed size. Example: http://referencesource.microsoft.com/#mscorlib/system/string.cs,64bbfbd0ad12230d – Hutch Jul 17 '15 at 22:15
  • Regarding your response `"Arrays must be assigned a length"` -- in a `static` method outside of `Main()`, I made the declaration `String[] tokens = null` and didn't initialize it but how come I was able to call `"Hello.World".Split('.')` on it without getting a `System.NullReferenceException` error? – Minh Tran Oct 11 '17 at 19:15
53

Use List<> to build up an 'array' of unknown length.

Use List<>.ToArray() to return a real array, and not a List.

var list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
var array = list.ToArray();
skwear
  • 563
  • 1
  • 5
  • 24
TFD
  • 23,890
  • 2
  • 34
  • 51
26

A little background information:

As said, if you want to have a dynamic collection of things, use a List<T>. Internally, a List uses an array for storage too. That array has a fixed size just like any other array. Once an array is declared as having a size, it doesn't change. When you add an item to a List, it's added to the array. Initially, the List starts out with an array that I believe has a length of 16. When you try to add the 17th item to the List, what happens is that a new array is allocated, that's (I think) twice the size of the old one, so 32 items. Then the content of the old array is copied into the new array. So while a List may appear dynamic to the outside observer, internally it has to comply to the rules as well.

And as you might have guessed, the copying and allocation of the arrays isn't free so one should aim to have as few of those as possible and to do that you can specify (in the constructor of List) an initial size of the array, which in a perfect scenario is just big enough to hold everything you want. However, this is micro-optimization and it's unlikely it will ever matter to you, but it's always nice to know what you're actually doing.

JulianR
  • 16,213
  • 5
  • 55
  • 85
17

You can create an array with the size set to a variable, i.e.

int size = 50;
string[] words = new string[size]; // contains 50 strings

However, that size can't change later on, if you decide you need 100 words. If you need the size to be really dynamic, you'll need to use a different sort of data structure. Try List.

mqp
  • 70,359
  • 14
  • 95
  • 123
  • 1
    These are all null. Try `string[] words = new string(',', size - 1).Split(',');` Now they're initialized with `""`. – Bitterblue Oct 27 '14 at 12:55
3

Use an ArrayList if in .NET 1.x, or a List<yourtype> if in .NET 2.0 or 3.x.

Search for them in System.Collections and System.Collections.Generics.

skwear
  • 563
  • 1
  • 5
  • 24
Diego Jancic
  • 7,280
  • 7
  • 52
  • 80
2

You might also want to look into Dictionarys if your data is unique, This will give you two columns to work with.

User name , Total bill

it gives you a lot of built in tools to search and update just the value.

Crash893
  • 11,428
  • 21
  • 88
  • 123
1

As detailed above, the generic List<> is the best way of doing it.

If you're stuck in .NET 1.*, then you will have to use the ArrayList class instead. This does not have compile-time type checking and you also have to add casting - messy.

Successive versions have also implemented various variations - including thread safe variants.

winwaed
  • 7,645
  • 6
  • 36
  • 81
1

If you really need to use an array instead of a list, then you can create an array whose size is calculated at run time like so...

e.g i want a two dimensional array of size n by n. n will be gotten at run time from the user

int n = 0;
bool isInteger = int.TryParse(Console.ReadLine(), out n);
var x = new int[n,n];
Pino
  • 7,468
  • 6
  • 50
  • 69
Ken Janka
  • 121
  • 3
  • 19
1
var yummy = new List<string>();
while(person.FeelsHappy()) {
    yummy.Add(person.GetNewFavoriteFood());
}
Console.WriteLine("Sweet! I have a list of size {0}.", list.Count);
Console.WriteLine("I didn't even need to know how big to make it " +
    "until I finished making it!");
yfeldblum
  • 65,165
  • 12
  • 129
  • 169
1

try a generic list instead of array

Hannoun Yassir
  • 20,583
  • 23
  • 77
  • 112
1

In a nutshell, please use Collections and Generics.

It's a must for any C# developer, it's worth spending time to learn :)

Novice
  • 883
  • 1
  • 10
  • 20