I have the following code:
static int rnd_nmb()
{
Random rnda = new Random();
int skw1 = rnda.Next(1, 11);
return skw1;
}
private void function1()
{
rnd_nmb1();
MessageBox.Show(Convert.ToString(skw1));
}
I want to reuse the variable skw1 to show it on a Message Box, but it says:
"the name 'skw1' does not exist in the current context.".
I don't know what the problem is. Btw. it's a Windows Forms App and i'm using Visual Studio 2019.
I added the 'return' statement and thought it would work, but it doesn't.
there is no need to reuse the local variable, since you wrote a method named rnd_nmb
which returns your desired value. Catch the returned value and use it:
private void function1()
{
int returnValue = rnd_nmb();
MessageBox.Show(returnValue.ToString);
}
I don't know what the problem is
One problem is the scope. The variable skw1
exists only withing the scope of the method in which it is declared. The scope is limited by {
and }
Second problem is that you need to use the correct names when you try to call a method. You declared rnd_nmb
but then you try to use rnd_nmb1
Third hint is that methods with a return value are exactly designed for the user to not care what happens inside of them. You use them and catch the result. It is like a toaster, you put bread in it and you catch the toasted stuff that come out in the end. You don't try to pull out the heating coil and use it on the bread, .... hopefully not... ;)