Nullreferenceexception

Asked

Viewed 113 times

3

I was doing tests, until I received the following error:

Object Reference Not Set To An Instance Of An Object

Researching found that it is the famous NullReferenceException, then I was obliged to do several checks on the code, as I show below, but I believe that doing all these checks is not good in relation to execution time, am I right? If I am there is another way to resolve this or to do these checks in a faster way?

var UrlApi2 = "api/EstoqueExterno/create";

if (ambienteViewModel.EstExt_endereco == null)
   ambienteModel2.EstExt_endereco = "";

else
   ambienteModel2.EstExt_endereco = ambienteViewModel.EstExt_endereco.ToUpper();

   ambienteModel2.EstTp_Codigo = ambienteViewModel.EstTp_Codigo;


if (ambienteViewModel.EstExt_senha == null)
    ambienteModel2.EstExt_senha = "";

else
    ambienteModel2.EstExt_senha = ambienteViewModel.EstExt_senha.ToUpper();

if (ambienteViewModel.EstExt_usuario == null)
    ambienteModel2.EstExt_usuario = "";

else
    ambienteModel2.EstExt_usuario = ambienteViewModel.EstExt_usuario.ToUpper();

2 answers

6


You can use the null coalescence operator ?? which returns left operand if the operand is not null and otherwise it will return right operand.

Using your last condition as an example:

if (ambienteViewModel.EstExt_usuario == null)
    ambienteModel2.EstExt_usuario = "";

else
    ambienteModel2.EstExt_usuario = ambienteViewModel.EstExt_usuario.ToUpper();

which can be rewritten as:

ambienteModel2.EstExt_usuario = (ambienteViewModel.EstExt_usuario ?? "").ToUpper();
  • 1

    Cool, saved me some lines of code kk, thanks

5

You can replace this code:

if (ambienteViewModel.EstExt_senha == null)
    ambienteModel2.EstExt_senha = "";

For that:

ambienteModel2?.EstExt_senha ?? "";

Adding the ? before the . is verified whether ambienteModel2 is null, if NOT, it calls the method EstExt_senha, if null is not executed the EstExt_senha. Already the ?? checks if there is any value in EstExt_senha, if the value is null (as per your example), assign " " the variable.

  • I like that code, there’s an extra check.

  • 3

    but what would be null was the property This password of environmentViewModel, could do was: ambienteModel2.EstExt_senha = ambienteViewModel.EstExt_senha?.ToUpper(); but would remain the null in the event of null and not "".

  • 1

    Yes, I believe the ambienteModel2? not necessary, but I liked the answer, I will accept Augusto’s because I found more complete to my problem, but I appreciate the help

  • Thanks for your thoughts, thanks!

Browser other questions tagged

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