NullReferenceException in C #

1

I have a problem in C #, I'm encountering an exception and I can not recognize why it is

Exception Details:

  

System.NullReferenceException: "Object reference not set to an instance of an object."

Excerpt of code that throws the exception is:

public void AdicionarCliente(String nome, String sobrenome)
{
    Clientes.Add(new Cliente(nome, sobrenome));
}

In class:

public sealed class Banco
{
    private static readonly Banco instance = new Banco();
    public static Banco Instance
    {
        get
        {
            return instance;
        }
    }

    private List<Cliente> Clientes;

    private Banco()
    {
    }

    public void AdicionarCliente(String nome, String sobrenome)
    {
        Clientes.Add(new Cliente(nome, sobrenome));
    }

    public int GetNumeroDeClientes()
    {
        return Clientes.Count;
    }

    public Cliente GetCliente(int indice)
    {
        return Clientes[indice];
    }
}

Client Class:

public class Cliente
{
    public String Nome
    {
        get;
        private set;
    }
    public String Sobrenome
    {
        get;
        private set;
    }
    private List<Conta> Contas { set; get; }

    public Cliente(String nome, String sobrenome)
    {
        this.Nome = nome;
        this.Sobrenome = sobrenome;
    }

    public Conta GetConta(int indice)
    {
        return Contas[indice];
    }

    public int GetNumeroDeContas()
    {
        return Contas.Count;
    }

    public void AdicionarConta(Conta c)
    {
        Contas.Add(c);
    }
}
    
asked by anonymous 17.07.2018 / 19:20

1 answer

4

This is because the client list was not instantiated.

I have no way to know when it's time to instantiate it, but if it goes right at startup you can do it right in the declaration

private List<Cliente> Clientes = new List<Cliente();
    
17.07.2018 / 19:23