fnicke fnicke -4 years ago 86
C# Question

Using data returned from methods

Please help me understand this if you can. I am only a few months into studying C# and seem to be missing something. I understand how to create methods, but can't seem to be able to retrieve the data to use outside of them. Please see this example I just created, trying to create a method that generates a number from 1 to 20 and then overwrite an existing variable.

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

namespace _170227
{
class Program
{


static void Main(string[] args)
{
int x = 0;

d20();
Console.WriteLine(x);

}


static int d20()
{
Random myRandom = new Random();
int x = myRandom.Next(20) + 1;
return x;


}

}

}


What do I need to do to have a method manipulate existing variables or generate data from a method for some further use not defined in the method itself? Thank you in advance!

Answer Source

The x inside the d20() method is not the same variable as the x in the scope from which you invoke d20. You need to tell the compiler that you would like to have the output from d20 stored inside the latter, with an assignment:

static void Main(string[] args)
{
    int x = 0;

    x = d20();
    Console.WriteLine(x);
}

You can declare and assign x in the same statement if you like:

static void Main(string[] args)
{
    int x = d20();
    Console.WriteLine(x);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download