How to show the output "This is a print name method" from a return statement. This is the code below thanks
class Print{
static string PrintName()
{
string output="This is a print name method";
Console.WriteLine(output);
return output;
}
static void Main()
{
Print.PrintName();
}
}
PS. When I set my Main() method's return type to string it gives me error that include static Main() method for an entry point.. Does this mean that Main() method can be only of a void return type as a standard return type just like the Main() method itself which has been declared as a standard method serving as an entry point for our programs to be executed and cannot directly execute our own defined methods in this case PrintName() method.
Thanks a bunch!
Sachin SinghPosted May 14, 2022, 9:30 AM
Yes, you are correct. The allowed return type of Main() method is void, int, Task(From C# 7.1), and Task(From C# 7.1).The return value of main() is just the exit status of the application.
so, when you return any int from Main() method it means the execution will stop there.
So, you need to create another method and call it from the main as
class Print{
public static string PrintName()
{
string output="This is a print name method";
Console.WriteLine(output);
return output;
}
static void Main()
{
Print.PrintName(); // it will print the stement as well as return the string
string str=Print.PrintName();
Console.WriteLine(str);
}
}
Sachin SinghPosted May 14, 2022, 12:18 PM
Shazma BatoolPosted May 14, 2022, 12:14 PM
Thanks @sachin singh that means we cannot directly print any string with a return statement rather it has to be stored in some string variable and then the Console.WriteLine() method used for its output to let one actually see the string output on the console
i.e
namespace Print
{
class Print
{
static string PrintName()
{
string output = "This is a print name method";
return output;
// return statement required as our method's return type is not void i.e. string PrintName()
}
static void Main()
{
string str = Print.PrintName();//using another variable to store "This is a print.." from the PrintName()
Console.WriteLine(str);// And passing it to Console.WriteLine() method in order to show it in a console window
//b/c return statement cannot return the string
}
}
}