C# – Assign a value from a string array to the string property of each element of a custom type array

arrayscnullreferenceexception

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 access countries[i].Name that object doesn't exist, and then .Name throws the exception.

So you need to initialize it:

for (int i = 0; i < 193; i++)
{
    countries[i] = new Country { Name = countryNames[i] };
}

A better way that using a for loop is using a foreach:

List<Country> countries = new List<Country>();
foreach(var countryName in countryNames
{
    countries.Add(new Country { Name = countryName });
}

And then from the foreach you can leap to linq:

string[] countryNames = { "Afghanistan", "Albania", "Algeria" };
var countried = countryNames.Select(item => new Country { Name = item });