0

My method returns a response object which contains a list of objects.

public class GetAccountsListResponse
{
    public List<AccountsList> Accounts { get; set; }
}

public class AccountsList
{
    public string AccountId { get; set; }
    public string AccountName { get; set; }

}

I tried something like this, but im getting null refernce exception :

public GetAccountsListResponse GetAccountsList()
    {

        AccountRepository objRepo = new AccountRepository();
        GetAccountsListResponse res = new GetAccountsListResponse();

        List<Account> lstAccnts = new List<Account>();
        lstAccnts = objRepo.GetAccountsFromRepo();

        foreach (var item in lstAccnts)
        {
            res.Accounts = new List<AccountsList>();
            res.Accounts.ForEach(c => c.AccountId = item.AccountId);    

        }

        return res;
    }

Please help me to fix the issue.

Imp
  • 27
  • 6
  • in which line you are getting this – BRAHIM Kamel Mar 05 '14 at 09:44
  • Looks like lstAccnts *might* be coming back null from the call `objRepo.GetAccountsFromRepo()`. – Baldrick Mar 05 '14 at 09:46
  • 2
    `res.Accounts = new List(); res.Accounts.ForEach(c => c.AccountId = item.AccountId);` These two lines doesn't makes sense. you create `new List<>` and `ForEach` ? It will always have zero elements – Sriram Sakthivel Mar 05 '14 at 09:47
  • @K.B im getting error in res.Accounts.ForEach(c => c.AccountId = item.AccountId); – Imp Mar 05 '14 at 09:52
  • @Baldrick no it is returning list of accounts – Imp Mar 05 '14 at 09:53
  • @Sriram Sakthivel can u pls help me fix the issue, if u have understood the question? – Imp Mar 05 '14 at 09:54
  • Check my answer [here](http://stackoverflow.com/questions/22146277/how-to-know-an-exact-location-of-nullreferenceexception/22146474#22146474) to track where the null reference exception happens. Then you can fix it by checking for null or instantiating new object. – Sriram Sakthivel Mar 05 '14 at 09:57
  • You start the confusion by naming an AccountItem an AccountList. And then there is your are creating (empty) lists everywhere. – H H Mar 05 '14 at 09:59

1 Answers1

3

that's obvious as you are only creating a new list with no object instantiated at all try something like this

    res.Accounts = new List<AccountsList>();
    foreach (var item in lstAccnts)
    {

        res.Accounts.Add( new AccountsList(){AccountId =item.AccountId});    

    }
BRAHIM Kamel
  • 13,492
  • 1
  • 36
  • 47