Jasmine Salmeron
Jasmine Salmeron

Reputation: 21

How can we return a string from one method to the main method?

I am trying to call the method PrintBanner from main. However, it won't let me.

static void Main(string[] args)
{
    string banner;
    banner = PrintBanner("This is whats supposed to be printed."); 
}

public static void PrintBanner()
{
    return PrintBanner(banner); 
}

I need the message to be called from main. But the error says that no overload for PrintBanner takes one argument. And that the name banner does not exist in PrintBanner.

Am I supposed to put string banner in PrintBanner method?

Upvotes: 2

Views: 876

Answers (2)

jPhizzle
jPhizzle

Reputation: 497

Oh boy... first off, your PrintBanner() method is void, therefore you won't be able to "return" anything.

Also, because your PrintBanner doesn't take any parameters, you can't pass any arguments to it.

Try this:

static void Main(string[] args)
{
    string banner = PrintBanner("This is what's supposed to be printed.")
    Console.WriteLine(banner); 
    Console.ReadLine();
}

//PrintBanner now has a string parameter named message (you can name it 
//whatever you want, but in the method in order to access that parameter, the 
//names have to match), thus when we call it in main, we can pass a string as 
//an argument
public static string PrintBanner(string message)
{
    return message;
}

Upvotes: 0

Norse
Norse

Reputation: 121

I'm unclear on what you are trying to accomplish here. Though it seems by your code that you want to both print and assign a value at with the PrintBanner method.

public static void Main(string[] args)
{
    string banner;
    banner = PrintBanner("This is whats supposed to be printed.");
}
public static string PrintBanner(string text)
{
    Console.Write(text);
    return text;
}

Or maybe you don't want the method itself to perform the assignment?:

public static void Main(string[] args)
{
    string banner;
    PrintBanner(banner = "This is whats supposed to be printed.");
}
public static void PrintBanner(string text)
{
    // The text variable contains "This is whats supposed to be printed." now.
    // You can perform whatever operations you want with it within this scope,
    // but it won't alter the text the banner variable contains.
}

If not, then please try to elaborate further on your goal.

Upvotes: 1

Related Questions