Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot convert from 'void' to 'bool'

I am learning C# and obviously having problem running my program, as I am running this on 'Ubuntu', means no Visual studio, but on Visual Studio code, so having problem with debugging stuff.

namespace BeginnerCSharp;

class Program        
{
    string testUser = "User 1";
    int age = 15;   

    void printMessage()
    {
        Program program = new Program();
        int user_age = program.age;
        if (user_age == 15)
        {
            Console.WriteLine("You are very young");
        }
    }

    static void Main(string[] args)
    {
        Console.WriteLine(program.printMessage());
    }
}

I am getting following error, at printMessage()

cannot convert from 'void' to 'bool'

What seems to be the problem, since I am not returning anything at all.

like image 244
qatesterbecomingprogrammer Avatar asked Oct 18 '25 19:10

qatesterbecomingprogrammer


2 Answers

static void Main(string[] args)
{
    Console.WriteLine(printMessage());
}

In your code : Console.WriteLine(printMessage()); This above line is giving the error: cannot convert from 'void' to 'bool'

As Console.WriteLine() function expects some value. But printMessage() is returning void thus you are getting that error.

There are 2 ways to get past the error:

  1. In this case you don't have to write: Console.WriteLine(printMessage());

    you can directly call the function as below :

static void Main(string[] args)
  {
      Program program = new Program();

      program.printMessage();
  }
  1. You can return something from printMessage() Something like this:
 int  printMessage()
 {
     Program program = new Program();
     int user_age = program.age;
     if (user_age == 15)
     {
         Console.WriteLine("You are very young");
     }
     return 0;
 }
like image 168
Sachin Diwate Avatar answered Oct 20 '25 09:10

Sachin Diwate


When your code modified as below then the CS1503 Argument 1: cannot convert from 'void' to 'bool' compile error is displayed.

static void printMessage()
{
    Program program = new Program();
    int user_age = program.age;
    if (user_age == 15)
    {
        Console.WriteLine("You are very young");
    }
}

static void Main(string[] args)
{
    Console.WriteLine(printMessage());
}

The problem is that all overloads of the Console.WriteLine method (except for the parameterless one) requires a value. Since printMessage() method has void return type (does not return any value), the line

Console.WriteLine(printMessage());

gives the error you provided. If you change the printMessage() method so that it returns a bool, int, double etc. then it will compile. Just make sure that your return type matches one of the Console.WriteLine() overloads.

like image 35
Mustafa Özçetin Avatar answered Oct 20 '25 10:10

Mustafa Özçetin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!