CS0029 Error - Cannot implicitly convert "int" to "bool" as a function of C#

Asked

Viewed 1,559 times

1

The code receives a user number and print if it is positive for True and if it is negative for False, only that there is a mistake of types going on and I don’t understand how to solve.

using static System.Console;

namespace F1
{
    class Program
    {
        static int Main(string[] args)
        {
            int numero;
            Write("Digite um número: ");
            numero = int.Parse(ReadLine());
            WriteLine($"{Verificar(numero)}");
            ReadKey();
            return 0;
        }

        public static bool Verificar(int numero)
        {
            if (numero > 0)
            {
                return true;
            }
            else if (numero < 0)
            {
                return false;
            }
            return numero;
        }
    }
}

2 answers

4


The error is exactly what it is showing, you are trying to return a number where one expects a boolean. And looking at the code doesn’t make any sense even to make that return. It would be interesting to interpret the error message and find where it is occurring.

In the case was that return numero; that it doesn’t make any sense to be there. If you want to return if you are positive or not just return the boolean, you have no reason to return the number, if you need to return the number you would need to do other things (and possibly change the name of the method), but without a requirement nor will I risk trying it, doesn’t look like you need this.

It would be that simple (note that I have fixed other problems that have been shown before and that you refuse to fix because it does not break the application in all cases:

using static System.Console;

class Program {
    static void Main() {
        Write("Digite um número: ");
        if (int.TryParse(ReadLine(), out var numero)) return;
        WriteLine($"{ÉPositivo(numero)}");
    }
    public static bool ÉPositivo(int numero) => numero >= 0;
}

Behold working in the ideone. And in the .NET Fidlle. Also put on the Github for future reference.

Have you noticed that the number of lines and characters in the code is much smaller and keeping a clean logic? And I also fixed a misinterpretation of what is a positive number (0 is also a positive). And I gave a significant name to the method, because if it is to give a name that does not mean anything or needed the method of so simple that it is and there could make the comparison directly in the code, but I understand that wants the abstraction of the method.

A boolean expression already results in boolean so there is no need to use a boolean if, in this case just return the result of the expression itself. It is necessary to understand what each thing does in the code otherwise you will never learn to program, you will only be repeating codes you have seen before somewhere.

Important to learn more about: Why does the if only work with the return of a method?.

  • I had not seen that I already had an answer. They say the same thing. I ask, the correct thing is to remove my answer?

  • 1

    There’s no reason, yours gives a different explanation.

4

The C# is statically typed at compile time, after a variable is declared, it cannot be declared again or assigned to a value of another type, unless that type can be converted implicitly into the type of the variable.

The signature of the method Verificar() specifies that the return type is bool. On the line...

return numero;

...is returned numero who’s kind int where the error occurs:

error CS0029: Cannot implicitly Convert type 'int' to 'bool'

You can identify two errors in your code:

  1. The attempt to return an integer in place of a logical value.
  2. His method Verificar() does not cover all the possibilities of numerical entries. If numero is equal to zero the method can classify because the checks are numero > 0 and numero < 0 and both do not include the case numero == 0.

Looking at the documentation of comparison operators C# it appears that relational operators ==, <, >, <= and >= compare their operands and return a bool.

Aware of this simply simplify the method Verificar() using a comparison that covers the entire numerical spectrum supported by the type int.

using static System.Console;

namespace F1
{
    class Program
    {
        static int Main(string[] args)
        {
            int numero;
            Write("Digite um número: ");
            numero = int.Parse(ReadLine());
            WriteLine($"{Verificar(numero)}");
            ReadKey();
            return 0;
        }

        public static bool Verificar(int numero)
        {
            // Se numero for maior ou igual a zero retorna true caso contrário retorna false.
            return numero >= 0;
        }
    }
}

Due to the simplicity of the operation performed within the 'Check()' method, it is possible to delete this method and transfer this comparison numero >= 0 inwarddo corpo do método Main().

using static System.Console;

namespace F1
{
    class Program
    {
        static int Main(string[] args)
        {
            int numero;
            Write("Digite um número: ");
            numero = int.Parse(ReadLine());
            WriteLine($"{numero >= 0}");
            ReadKey();
            return 0;
        }

    }
}
  • It is necessary to use the method Verificar()

  • @Carlosa., imagining this possibility that I put two codes in answer one with Verificar() and the other without Verificar()

  • This way without the method is also interesting that returns the result.

Browser other questions tagged

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