I have the following class
public class ResProductSetupData
{
public List<ProductSetup> data { get; set; }
}
public class ProductSetup
{
public List<Fundtype> FundType { get; set; }
}
public class Fundtype
{
public string FundType { get; set; }
public bool IsGIO { get; set; }
public string ReportCode { get; set; }
public List<Fundlist> FundList { get; set; }
}
public class Fundlist
{
public string FundCode { get; set; }
public string FundDesc { get; set; }
public decimal MinAllocation { get; set; }
public string VPMSField { get; set; }
public string FundSpec { get; set; }
}
Now I want to initialize this object inside another file so that I can fill its values. Fundtype is a list and FundList is another list inside FundType.
ProductSetup prodSetup = new ProductSetup();
Fundtype fundType = new Fundtype();
Fundlist fundlist = new Fundlist();
So Inside a foreach loop I instantiated these objects
prodSetup.FundType = new List<Fundtype>();
foreach (var fund in fundTypeData)
{
fundType.FundType = fund.FundType;
fundType.IsGIO = fund.IsGIO;
fundType.ReportCode = "";
prodSetup.FundType.Add(fundType);
var listOfFund = GetProductFund(prodSetup.ProdCode, fund.FundType);
int i = 0;
foreach (var listFundData in listOfFund)
{
var fundDetails = GetFundDetails(listFundData.FundCode);
fundlist.FundCode = listFundData.FundCode;
fundlist.VPMSField = listFundData.VPMSField;
fundlist.FundDesc = fundDetails[0].FundDesc;
fundlist.MinAllocation = fundDetails[0].MinAllocation;
fundlist.FundSpec = fundDetails[0].FundSpec;
prodSetup.FundType[i].FundList.Add(fundlist);
i++;
}
}
When I add data into the Fundlist list, an error will show System.NullReferenceException: 'Object reference not set to an instance of an object.'. I know I have to instantiate first, but I dont know how. Any help would be appreciated.
Update, I have instantiated the FundList array as below
int i = 0;
foreach (var listFundData in listOfFund)
{
prodSetup.FundType[i].FundList = new List<Fundlist>();
var fundDetails = GetFundDetails(listFundData.FundCode);
fundlist.FundCode = listFundData.FundCode;
fundlist.VPMSField = listFundData.VPMSField;
fundlist.FundDesc = fundDetails[0].FundDesc;
fundlist.MinAllocation = fundDetails[0].MinAllocation;
fundlist.FundSpec = fundDetails[0].FundSpec;
prodSetup.FundType[i].FundList.Add(fundlist);
i++;
}
The first index [0] is fine. But when it loops to the second index to instantiate the second index [1], it throws another error Index was out of range. Must be non-negative and less than the size of the collection.\r\nParameter name: index