Check if int is "null" in C#

Asked

Viewed 8,025 times

8

Cannot assign on C# null at an integer value (int, nay int?).

However, how can I know if an integer value (int) has not yet had an assigned value (being of the type int)?

int? valor;
if (valor == null)
{
   // Isso pode
}

However..

int valor;
if (valor == null)
{
   // Isso não
}

How to check if an integer has not yet received any value?

  • Transform into String and then check the contents with the method equals() could not be?

4 answers

10


A type by value will always have assigned a value. You declared the variable and it entered the scope has a value. If the code does not define any it will be adopted the default value that is 0.

If you need to define whether a variable had a value and then passed or did not have another value, you have to control it separately in another variable: either telling if you had a value change; or what the original value was to see if it is still the same, which gives a slightly different semantics.

When a variable is worth 1 and you assign a value 1 in it you changed the value of the variable, but the result is the same, just make no mistake that there is another object there, but that has the same content. If you just want to know if the value is different have the previous value seems the most appropriate. If you want to know if a new value has been assigned to the variable, but it doesn’t matter if it has been changed, then a flag is more useful. The int? has a flag, in some cases may be sufficient, as long as it does not let the value be null after.

You can create a guy to control that, but by description you can’t do this in this case.

5

In C#, a int cannot be null, if you need it to be null you will have to declare it as Nullable<int> or in its sugar syntax int?.

  • Thanks for your reply, but in case I can’t use "int?" because I am implementing an interface that defined the value as int, but in certain cases the int value has not yet received any value. I would need to do a check and would like to know if this is possible.

  • @Renancavalieri in this case, will probably give error of using a variable that was not initialized or depending on how this value is coming, it may be that it takes its default value, in the case is 0.

  • If the interface design predicts an int, wouldn’t null be an error? Or you’re wanting to return what you shouldn’t or the interface was poorly designed. Review the purpose of the implementation and, if applicable, make the appropriate error handling.

2

In case you can use the "Hasvalue"

    int? valor;
   if (valor.HasValue)
    { 
      int valorDaVariavelValor = valor.value;
    }

-2

Dude, for me, the most crooked way there is is to convert to string, use any() and also an Arrow Function. value type.tostring(). Any() ? " Not null" : "is null"

Browser other questions tagged

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