KeyValuePair array initialization

This seems like a simple task, but I don't seem to be able to work out the correct syntax. I currently have this:

KeyValuePair<string, string>[] kvpArr = new KeyValuePair<string,string>[]; 

However, this seems to work:

 KeyValuePair<string, string>[] kvpArr = new KeyValuePair<string,string>[10]; 

But I do not know the size of the array initially. I know that I can use the KVP list, and I probably will, but I just wanted to know how to do it / if it really can be done.

+6
arrays c #
source share
4 answers

No, you cannot do this because the array always has a fixed size. If you do not specify this size for starters, what size do you expect to use? You either need to specify the size itself, or the content (which allows you to determine the size). For example:

 int[] x = new int[10]; // Explicit size int[] y = new int[] { 1, 2, 3, 4, 5 }; // Implicit size int[] z = { 1, 2, 3, 4, 5 }; // Implicit size and type 

List<T> definitely your friend for collections where you don’t know the size to start with.

+8
source share

Why not use

 List<KeyValuePair<string, string>> 

See List Class

+7
source share

Arrays are, by definition, fixed. You can specify the size, as in your second code example, or you can get it from initialization:

 KeyValuePair<string, string>[] kvpArr = new KeyValuePair<string, string>[] { new KeyValuePair<string, string>(...), new KeyValuePair<string, string>(...), ... } 

If you need a variable-length structure, I suggest you use List<T> .

For more information about arrays, see the C # Programming Guide .

+7
source share

How about this?

 var kvpArr = new List<KeyValuePair<string,string>>(); 
+1
source share

All Articles