Suppose I have an array of strings – countryNames[]
– containing the names of the countries in the world:
string[] countryNames = { "Afghanistan" , "Albania" , "Algeria", ... }
I also have a class called Country
containing these properties, among others:
public string CountryCode { get; set; }
public string Name { get; set; }
My goal is to create an array of the custom type Country
, and assign to the Country.Name
property of each element of Country[]
the corresponding index's string value of countryNames[]
. I tried doing so in the following way, in the same method where I implemented the string array:
Country[] countries = new Country[193];
for (int i = 0; i < 193; i++)
{
countries[i].Name = countryNames[i];
}
return countries;
The countries[i].Name
however, causes a NullReferenceException
. I can't see where the problem is though, as the property Country.Name
is a string. Are there any complications when arrays and properties are mixed together?
Thanks guys!
Best Answer
The reason why you get a
NullReferenceException
is that when you initialize an array of object it doesn't initialize the items within it. Meaning that when you accesscountries[i].Name
that object doesn't exist, and then.Name
throws the exception.So you need to initialize it:
A better way that using a for loop is using a
foreach
:And then from the foreach you can leap to linq: