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.
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:
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();
}
int printMessage() { Program program = new Program(); int user_age = program.age; if (user_age == 15) { Console.WriteLine("You are very young"); } return 0; }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With