Will Miles
Will Miles

Reputation: 51

How to return a string and use it in another static void?

I'm trying to create two methods. The first one will return a string and the other one will use the string that the first method returned. At least that's what I'm trying to do...

public string Name()
{
    string x = "I need help"
    return x;
}
static void Print()
{
    Console.WriteLine(x);
}

But it keeps saying that the string x does not exist in the current context.

Upvotes: 0

Views: 1486

Answers (4)

nzrytmn
nzrytmn

Reputation: 6951

The first method should be static too , otherwise you can not call a non static method in a static method. So you can do like this:

public static string Name()
{
 string x = "I need help"; // You forgot a ; at your code 
 return x;
}
static void Print
{
  Console.WriteLine(Name());
}

Upvotes: 1

Nolan Bradshaw
Nolan Bradshaw

Reputation: 484

Your code should look something like this:

public static string Name()
{
   string x = "I need help";
   return x;
}

public static void Print()
{
    Console.WriteLine(Name());
}

Upvotes: 0

Jon
Jon

Reputation: 6056

public static string Name()
{
    string x = "I need help";
    return x;
}
public static void Print()
{
    string x = Name();
    Console.WriteLine(x);
}

Upvotes: 0

Mikael
Mikael

Reputation: 982

public static string Name()
{
    string x = "I need help";
    return x;
}
static void Print(string x)
{
    Console.WriteLine(x);
}

You would use it like:

string name = Name();
Print(name);

Try it out here: https://dotnetfiddle.net/20HVyh

Upvotes: 0

Related Questions