Reputation: 2811
I have a list that I declare as follows:
List<Person> persons = new List<Person>();
In another part of my code I initialize and populate the list using a LINQ query and get the data from an xml file. That's not really important to note here. The only thing to know is that the list is initialized and confirmed populated with data.
Another part of my code uses a WCF service to look up the people in my list and get their associated data. In the code below, the variable ret
holds this data.
ServiceClient client = new ServiceClient();
MyService.Person p = new MyService.Person();
for (int i = 0; i < persons.Count; i++)
{
p.PersonID = persons[i].PersonID;
p.FName = persons[i].FName;
p.LName = persons[i].LName;
var ret = client.GetFees(new MyService.Person[] { p });
for (int j = 0; j < ret[0].Fees.Length; j++)
{
persons[i].Fees[j] = ret[0].Fees[j].Amount;
}
}
client.Close();
What I want to do is take the Amount data from the ret variable and assign it all into the persons list fee attribute. In the above code, this take place on this line:
persons[i].Fees[j] = ret[0].Fees[j].Amount;
The problem is I keep getting this error from Visual Studio on that line:
I think it has something to do with the Fees array attribute of the persons list object not being initialized, or something like that.
If the case was that I had a person object of the class Person with a list property, I would initialize it like this:
Person p = new Person();
p.Fees = new List<double>();
But that's not the case here. So what do I do in this situation? In other words, how do I fix persons[i].Fees[j] = ret[0].Fees[j].Amount;
to not throw a null reference exception??
My ultimate goal is to get the fee data in the fee attribute of the persons list so that I can later sort the list using the OrderBy method. But for now I just need to get rid of this error.
Thanks in advance for reading. Please help.
Upvotes: 0
Views: 146
Reputation: 32681
in your for loop do this
for (int j = 0; j < ret[0].Fees.Length; j++)
{
if(persons[i].Fees == null)
persons[i].Fees = new List<double>();
persons[i].Fees[j] = ret[0].Fees[j].Amount;
}
Upvotes: 1