How to convert a nullable int to common int

Asked

Viewed 1,349 times

4

I have a method that gets an integer that can be null, if it happens some executions of methods, but when I will use the same variable in a place that uses int which cannot be null, it appears that the overload is incorrect.

So I wonder how I can make this conversion, is there any method that does it like ToString?

Code with the problem

public HttpResponseMessage Metodo(int? variavel = chamadademetodo.metodo {

            if (variavel == null) {
                ...
            }

            var bla2= blablabla.metodo(variavel, DataContext); //aqui acusa problema
}
  • variavel = chamadademetodo.metodo that doesn’t exist.

  • @bigown doesn’t exist, it was just for example

  • I wonder if you really need this int? there.

  • @accurate mustache, this app is also mobile and if the int is not nullable, it can interfere with the app’s behavior

  • Everything you do can affect how it works, but a lot of things can be done in a better way. Just like you can use dynamic (in your previous question), there is a better way, this is a case that may have better solution.

  • I understand, maybe there is a better way, but this would involve moving around a lot of places and/or demanding knowledge that I don’t have yet

Show 1 more comment

2 answers

7


You can also use:

int variavelNNula = variavel.GetValueOrDefault();

In case the int default would be zero.

5

Normally, the following technique solves:

public HttpResponseMessage Metodo(int? variavel)
{
    var variavelNaoNula = variavel ?? 0;

    var bla2= blablabla.Metodo(variavelNaoNula, DataContext);
}
  • what use are the "??"

  • It is an operator called coalescence. If the left side is null, it assigns the right side.

  • @Paz https://answall.com/q/44133/101, not for this case, but also: https://answall.com/q/91785/101

  • sensational, thanks @bigown

  • 1

    thanks for the @Ciganomorrisonmendez explanation

Browser other questions tagged

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