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.
3
Answers
Alright someone commented the correct answer and the removed it.. Yes, I have to remove
Console.WriteLine
fromMain
Method. and It worked.When your code modified as below then the
CS1503 Argument 1: cannot convert from 'void' to 'bool'
compile error is displayed.The problem is that all overloads of the
Console.WriteLine
method (except for the parameterless one) requires a value. SinceprintMessage()
method hasvoid
return type (does not return any value), the linegives the error you provided. If you change the
printMessage()
method so that it returns abool
,int
,double
etc. then it will compile. Just make sure that your return type matches one of theConsole.WriteLine()
overloads.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 :
Something like this: