Object error not instantiated

Asked

Viewed 250 times

1

I have a model calling for ClientesModel. Inside it I have the fields:

    public int id { get; set; }
    public int codcli { get; set; }
    public string nome { get; set; }
    public string endereco { get; set; }
    public string nr { get; set; }
    public string bairro { get; set; }
    public string cidade { get; set; }

I also have a model called states with the following fields:

    public int id { get; set; }
    public string sigla { get; set; }

How would you do to link these two models? I tried to do so:

    public int id { get; set; }
    public int codcli { get; set; }
    public string nome { get; set; }
    public string endereco { get; set; }
    public string nr { get; set; }
    public string bairro { get; set; }
    public string cidade { get; set; }
    public EstadosModel estado { get; set; } 

And by putting the information on model, use in that way:

    ClientesModel c = new ClientesModel();
    c.id = Convert.ToInt32(Dr["id"]);
    c.codcli = Convert.ToInt32(Dr["codcli"]);
    c.nome = Convert.ToString(Dr["nome"]);
    c.endereco = Convert.ToString(Dr["endereco"]);
    c.nr = Convert.ToString(Dr["nr"]);
    c.bairro = Convert.ToString(Dr["bairro"]);
    c.cidade = Convert.ToString(Dr["cidade"]);
    c.estado.id = 1;
    c.estado.sigla = Convert.ToString(Dr["sigla"]);

But ends up presenting error.

Object Reference not set to an instance of an Object.

I know I need to instantiate the object but not without where or how to instantiate an object.

I don’t know if I’m making a mess, too models separated.

2 answers

3


If I specifically address your problem, the object c.estado needs to be instantiated before you assign some value to properties id and sigla.

You can accomplish this in the method itself:

ClientesModel c = new ClientesModel();
c.id = Convert.ToInt32(Dr["id"]);
c.codcli = Convert.ToInt32(Dr["codcli"]);
c.nome = Convert.ToString(Dr["nome"]);
c.endereco = Convert.ToString(Dr["endereco"]);
c.nr = Convert.ToString(Dr["nr"]);
c.bairro = Convert.ToString(Dr["bairro"]);
c.cidade = Convert.ToString(Dr["cidade"]);
//Instanciando um novo estado e atribuindo sua referência a c.estado
c.estado = new EstadosModel();
c.estado.id = 1;
c.estado.sigla = Convert.ToString(Dr["sigla"]);

You can also put a default constructor in the Clientesmodel class:

public int id { get; set; }
public int codcli { get; set; }
public string nome { get; set; }
public string endereco { get; set; }
public string nr { get; set; }
public string bairro { get; set; }
public string cidade { get; set; }
public EstadosModel estado { get; set; } 
//Construtor padrão
public ClientesModel()
{
     this.estado = new EstadosModel();
}

Notes

  • Properties in c# follow the nomenclature Pascalcase (i.e first letter of each uppercase word, for example: Codigoclient)
  • Give preference to a more readable code than to a more streamlined code. No need (at first glance at least) for example to abbreviate the property codcli, or the property numero.
  • Whenever creating a new variable, try to make your name as explanatory as possible. In complex or extensive codes, this feature can be a very large differential for the correct understanding of the code without a great effort.
  • When naming your classes, use the plural only when it makes sense. If your class represents only one customer, it makes no sense to put your name in the plural (clients). Same for status and states. A good example to use the plural is in properties that are lists, which represent more than one object.

Following the above recommendations, your code would look something like this:

Clientemodel.Cs

public int Id { get; set; }
public int CodigoCliente { get; set; }
public string Nome { get; set; }
public string Endereco { get; set; }
public string Numero { get; set; }
public string Bairro { get; set; }
public string Cidade { get; set; }
public EstadoModel Estado { get; set; } 

Estadomodel.Cs

public int Id { get; set; }
public string Sigla{ get; set; }

Main.Cs

ClienteModel cliente = new ClienteModel();
cliente .id = Convert.ToInt32(Dr["id"]);
cliente.codcli = Convert.ToInt32(Dr["codcli"]);
cliente.nome = Convert.ToString(Dr["nome"]);
cliente.endereco = Convert.ToString(Dr["endereco"]);
c.nr = Convert.ToString(Dr["nr"]);
cliente.bairro = Convert.ToString(Dr["bairro"]);
cliente.cidade = Convert.ToString(Dr["cidade"]);
cliente.estado.id = 1;
cliente.estado.sigla = Convert.ToString(Dr["sigla"]);
  • 1

    Thank you so much for the tips.. I am now starting to develop in Layers and although I am doing Analysis College, I have not yet reached this subject and I am without whom to ask some basic questions.. With respect to the default Constructor public Clientesmodel() { this.Stateosmodel = new Stateosmodel(); } would not be: public Clientedel() { this.status = new Status(); }

  • Exactly. Corrected ^^

  • Oh yes.!! You are Kra.!! Thank you very much for the help..!!

1

Vinicius' answer is perfect, at least to the extent that it gives on top of the presented code (I won’t go into details of what could be different than what is not the focus of the question). I’ll just show you another way to initialize the object if you’re using C# 6 up:

public EstadosModel Estado { get; set; } = new EstadosModel();

So you don’t have to have the builder, at least not for this.

Another possible improvement is to use initialization and object:

var cliente = new ClienteModel {
    id = Convert.ToInt32(Dr["id"]),
    codcli = Convert.ToInt32(Dr["codcli"]),
    nome = Dr["nome"],
    endereco = Dr["endereco"],
    nr = Dr["nr"],
    bairro =Dr["bairro"],
    cidade = Dr["cidade"],
    estado.id = 1,
    estado.sigla = Dr["sigla"]
};

I put in the Github for future reference.

How I imagine the die comes as string in this dictionary, there is no reason to convert to string.

Note that if there is any reason for the data to be poorly formed, the Convert.ToInt32() will generate an exception, this is not the ideal.

Are you sure the client code needs to be numerical?

And while making style notes, follow the C style guide#.

  • Bigown.. Thanks for the tips... Seized the opportunity... How would you improve the code? I’m thinking of separating the address and tbm have a separate phone table with name and phone... How would you model this class..?

  • It is already too long to say here, it is another problem. And it would need a larger context of the application. I’ll give you an example: having a table with only one state acronym seems exaggerated to me. It comes out cheaper and it is simpler to put the direct acronym.

  • I get it... the idea is to have cities, states and ceps placed at the base.. With a desktop application, you may not lose performance

  • Then you start to have something completely different, yet it doesn’t seem to make sense. Even if it does, it makes little sense to prepare a part of the data for the future and leave a part simply. Interestingly it makes even more sense (not that it makes complete) for the city and other data to be separated into a class, and this was not done.

Browser other questions tagged

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