Home > Enterprise >  How to take 'snapshot' of variable value before a for loop? C#
How to take 'snapshot' of variable value before a for loop? C#

Time:07-06

     static void Main(string[] args)
    {
        Random rnd = new Random();

        float  myfloat = rnd.Next(1, 50);

        for (int i = 0; i <= 2; i  )
        {
            myfloat = 3;
        }
        Console.WriteLine(myfloat);
        Console.ReadLine();
    }

Say I want to change the value of a variable for the duration of a for loop, but then I want it to go back to whatever it was just befoe the loop (if i don't know what that value was). How would I do something like that?

With this code 'myfloat' is stuck at 3 after the loop ends.

CodePudding user response:

I recommend using a "temporary" variable.

static void Main(string[] args)
{
    Random rnd = new Random();

    float  myfloat = rnd.Next(1, 50);
    float  tempFloat = myfloat;

    for (int i = 0; i <= 2; i  )
    {
        myfloat = 3;
    }

    myfloat = tempFloat;
    Console.WriteLine(myfloat);
    Console.ReadLine();
}

It could look something like this.

  • Related