Check if int is "null" in C #


In C # it is not possible to assign null to an integer value ( int , not int? ).

However, how can I tell if an integer value ( int ) has not yet had an assigned value (being int )?

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

However ..

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

How to check if an integer has yet to receive any value?

asked by anonymous 15.08.2017 / 17:10

3 answers


One type per value will always have a value assigned to it. Declared the variable and it entered the scope has a value. If the code does not set any one will be adopted the default value that is 0.

If you need to define if a variable had a value and then passed or not have another you have to control this separately in another variable or saying if it had a change in value or what was the original value 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 of 1 in it you have changed the value of the variable, but the result is the same, just make no mistake that there is another object there, but it has the same content. If you only want to know if the value is different then having the previous value seems the most appropriate. If you want to know if a new value has been assigned to the variable, but it does not matter if it has been changed, then a flag is more useful.

You can create a type to control this, but by description you can not do this in this case.

15.08.2017 / 17:29

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

15.08.2017 / 17:17

In case you can use the "HasValue"

    int? valor;
   if (valor.HasValue)
      int valorDaVariavelValor = valor.value;
21.08.2017 / 14:23