rw_ rw_ - 3 years ago 151
C# Question

Why do I get an error when List<object>.Add(int)

I have an array of List types:

List<object> vector = new List<object>[3];


The first List contains strings:

// Get word lists together, remove duplicates
var words = tableA.ToList().Union(tableB.ToList());
// Sort words
words = words.OrderBy(s => s, StringComparer.CurrentCultureIgnoreCase);
// Add words to the vector first slot
vector[0] = words.ToList<object>();


Now, I want to add ints to the second and third lists, but I get an error here:

vector[1].Add(tableA.GetValue(keyword));
vector[2].Add(tableB.GetValue(keyword));


GetValue() returns an int. But when I add these ints to the vector Lists it throws error:

ERROR Caught: Object reference not set to an instance of an object.


How should I add the ints to the List? Or is there some other data structure I should use instead for the vector? I feel there is some trivial cast I'm missing but I haven't been able find a solution.

Answer Source

I'm not an expert in C#, but i think i understand. When you write :

List<object> vector = new List<object>[3];

you create an instance of List, or a table of List with a size of 3 maybe. You can put everything inot this list/array, but each "slot" still refers to no instance. When you write

vector[0] = words.ToList<object>(); 

You put somehting into the first slot of vector. But [1] and [2] are still empty. And

vector[1]

refers to a reference not set to an instance of an object. In short terms, it refers to nothing.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download