-6

When I do:

List<Person> person = new List<Person>();
person.Print();

I do not get anything (null)
However, when I do:

Person[] person2 = new person[10];
person2.Print();

I get an Exception.
Why? what happens in the memory? I dont get it.

Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
N3wbie
  • 227
  • 2
  • 13
  • 2
    Show us the `Print` method. – Dmitri Trofimov Apr 21 '16 at 10:05
  • 2
    `new person[10];` should be `new Person[10];`. – Salah Akbari Apr 21 '16 at 10:05
  • 1
    There is no `List.Print` or `Array.Print` method. Where does it come from? Is it an extension method? If so, where is it? – Patrick Hofman Apr 21 '16 at 10:05
  • Most probably an extension method – Viru Apr 21 '16 at 10:06
  • but your title is very bad – Viru Apr 21 '16 at 10:06
  • where is this Print method? and what error are you getting? – Mukund Apr 21 '16 at 10:07
  • So there is an extension method `Print` that takes an `IList` or `IList`? Show it, then we can help to fix it. – Tim Schmelter Apr 21 '16 at 10:07
  • what exception do you get, what is `person`, what is `Print`? – Jodrell Apr 21 '16 at 10:07
  • The base difference between a `List` and an array is that the list doesn't have items until you `Add` them. An array has already allocated the memory and you can access any index in the array, no matter if there is already an item there or not. – Patrick Hofman Apr 21 '16 at 10:08
  • In general, a list or array are collections, their purpose is to store multiple items, in this case persons. If you have an extension that prints them it expects that you pass a collection that contains anything. Your list is empty, so nothing to print. The array's length is 10 but all persons are null references. You have to loop the array and initialize all. – Tim Schmelter Apr 21 '16 at 10:12

2 Answers2

2

Ok,

var people = new Person[10]

is roughly equivalent to

var people = new List<Person>
   {
       default(Person),
       default(Person),
       default(Person),
       default(Person),
       default(Person),
       default(Person),
       default(Person),
       default(Person),
       default(Person),
       default(Person)
   }

now, I suspect your implementation of Print, which presumably extends IList<Person> doesn't handle default(Person).


var people = new List<Person>();

is actually more equivalent to

var people = new Person[0];

Does your Print implementation work with that?

Jodrell
  • 34,946
  • 5
  • 87
  • 124
1

I suggest you to update your method with a null check before doing nothing.

You are using them in different way as @Jodrell says in his answer.

With new person[0] you are initializing it with 0 references. But if you use 10, you are creating 10 references to null. The List contains nothing.

I think in your Print method your are doing a loop over the collection and with the List you don't have nothing to loop, but with the array you loop over 10 null references, which causes you Exception.