complex typed array and generic list in c#?

i want to create an array of complex object, and add its elements to a generic list of the same type, but when i try to access and manipulate individual elements of the array(non generic), i always indicate me NullReferenceException, i cannot invoke object that are not instantiated, what is the problem and how to fix it?

1 Answer

  • 1 year ago

    You have nearly answered your own question.  You must "instantiate" objects before you can use them.  That's true in a simple variable, and it's true for each position in an array.

    You can "fix" the exception by either putting non-null entries into every position of the array, or by using an if statement to skip over and ignore null entries (assuming you're using a loop to add array elements to the List<> data structure.)

    You haven't shown any code, nor really explained what it is you are trying to do.  Why are you putting values into an array, only to copy them into list?  If you need a collection to hold the entries you are going to add to a list, why not make that collection another list?  A List<> or LinkedList<> will resize itself to hold just the number of entries you put into it, so you'll never get a null reference out of one (unless you deliberately put one in.)

Still have questions? Get answers by asking now.