Joe Thorpe Joe Thorpe - 2 days ago 4
C# Question

How to pass a string from one method to the Main method?

I'm trying to pass a string from one method to my Main method.

The program is a C# console application. It's supposed to have the user input their first name, last name and birth place, and then reverse each of those and output them again. (e.g. Bob Tabor America -> boB robaT aciremA)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelperMethods
{
class Program
{
static void Main(string[] args)
{
GetString();
DisplayResult(ReverseString(input));

}
private static string GetString()
{
Console.WriteLine("The Name Game");

Console.Write("What's your first name? ");
string firstName = Console.ReadLine();

Console.Write("What's your last name? ");
string lastName = Console.ReadLine();

Console.Write("In what city were you born? ");
string birthPlace = Console.ReadLine();

string input = firstName + " " + lastName + " " + birthPlace;
return input;
}


private static string ReverseString(string message)
{
char[] messageArray = message.ToCharArray();
Array.Reverse(messageArray);
return String.Concat(messageArray);
}

private static void DisplayResult(string result)
{
Console.Write("Results: " + result);
}

}
}


Note how i'm trying to pass the string input from GetString() to the main method.

The given error is this:


The name 'input' does not exist in the current context


What should I do?

Answer

Try this:

static void Main(string[] args)
{
   string input = GetString();
   DisplayResult(ReverseString(input));
}
Comments