0

First of I call a method from the main program file:

Console.Write("Enter the ID number: ");

userbirthdate = Console.ReadLine();
int searchID = int.Parse(userbirthdate);

Console.Write("This is the new account number: ");
Console.WriteLine(bankLogic.AddSavingsAccount(searchID));

And the method that I call looks like this:

public int AddSavingsAccount(long idNumber)
    {
        accountgiver++;

        for (int i = 0; i < customers.Count; i++)
        {
            if (customers[i].BirthDate == idNumber)
            {
                SavingsAccount savingsaccount = new SavingsAccount();

                savingsaccount.saldo = 0;
                savingsaccount.interest = 0.01;
                savingsaccount.accountType = "Savingsaccount";
                savingsaccount.accountNumber = accountgiver;

                customers[i].customerAccounts.Add(savingsaccount);

                return savingsaccount.accountNumber;
            }
        }
        return 0;
    }

This code is in one of my three classes and this class is where I do all my methods.

There is another class in my program called "Customers" that holds three objects (Name, BirthDate and CustomerAccounts). CustomerAccounts is a List object which holds the SavingsAccount class (the third class).

What I want to accomplish is to add the saldo, intrest, accountType and accountNumber to the new savingsaccount and return the accountNumber. I can run this code but when the method gets called this error pops up "Object reference has not been specified to an instance of an object." and highlights this line:

customers[i].customerAccounts.Add(savingsaccount);

Why does this happen? I hope you understand what I want to achieve.

I'm new to C# so please be kind to me :) Thanks for answers!

Exibe
  • 1
  • 1
  • In your class called `Customers`, in the constructor set the `customerAccounts` list to a new list so whenever you create a new instance, the `customerAccounts` will be created too. – CodingYoshi Nov 04 '17 at 16:07
  • `BirthDate` as `int` is a bit weird. Either it is a date, then store it in a `DateTime` property or field, or it is an `int` ID, then call it `CustomerID`. – Olivier Jacot-Descombes Nov 04 '17 at 16:14

1 Answers1

0

The List customerAccounts you want to add other items to is probably not being initialized so its just null. Could you please post the Code from Customer class or try changing the declaration from the customersAccount list to

public List<SavingsAccount> customerAccounts = new List<SavingsAccount>();
Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188