0

I've got 2 functions each for specific button, which on of them finds random number and I want second function to only use that number without generating it again. I've tried to do in many ways, now my code is a little experimental but I didn't find a proper way to do it.

public partial class Form1 : Form
{
    public int ShuffleNor(int l)
    {
        int r = 0;
        string[] nor = File.ReadAllLines(@"C:\Users\Kapi\Desktop\no.txt").ToArray();
      
        Random rnd = new Random();
        r = rnd.Next(0, nor.Length);
        lbl_nor.Text = nor[r];
        return r;
            
    }
    public Form1()
    {
        InitializeComponent();
    }

    private void btn_shuffle_Click(object sender, EventArgs e)
    {
        ShuffleNor(1);
    }

    private void btn_check_Click(object sender, EventArgs e)
    {
       string[] eng = File.ReadAllLines(@"C:\Users\Kapi\Desktop\en.txt").ToArray();
       lbl_eng.Text = eng[ShuffleNor(0)];
    }
}
2
  • Usually, one would create a separate class and move all calculations in there. Commented Nov 13, 2021 at 13:04
  • 4
    Just declare a member variable. Declare it outside methods but inside the class. Commented Nov 13, 2021 at 13:19

2 Answers 2

1

the answer of tia is correct:

public partial class Form1 : Form
{
    public int ShuffleNor(int l)
    {
        int r = 0;
        string[] nor = File.ReadAllLines(@"C:\Users\Kapi\Desktop\no.txt").ToArray();
      
        Random rnd = new Random();
        r = rnd.Next(0, nor.Length);
        lbl_nor.Text = nor[r];
        return r;
            
    }
    public Form1()
    {
        InitializeComponent();
    }

    int _lastShuffleResult = 0;
    private void btn_shuffle_Click(object sender, EventArgs e)
    {
        _lastShuffleResult = ShuffleNor(1);
    }

    private void btn_check_Click(object sender, EventArgs e)
    {
       string[] eng = File.ReadAllLines(@"C:\Users\Kapi\Desktop\en.txt").ToArray();
       lbl_eng.Text = eng[_lastShuffleResult];
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Declare a variable at class scope:

public partial class Form1 : Form
{
   private int r;
   public int ShuffleNor(int l)
   {
      r = 0;
   [...]

If you make it public it will be visible to code that references instances of the class object. If you make it static, the same value/storage is used by all instances of the class.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.