Nullreferenceexception in C#

Asked

Viewed 32 times

1

I’m having a problem in C#, I’m facing an exception and I can’t recognize why

Details of the Exception:

System.Nullreferenceexception: "Object reference not defined for an instance of an object."

Code snippet 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);
    }
}

1 answer

4


This is because the customer list has not been instantiated.

I have no way of knowing what is the right time to instantiate it, but if it is right at startup you can do right at the declaration

private List<Cliente> Clientes = new List<Cliente();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.