0
DateTime theMonth = DateTime.Now;
for(int i = 0; i<8; i++){
     string curMonth = theMonth.AddMonths(-i).ToString("MM/yyyy");
}

Or,

DateTime theMonth = DateTime.Now;
string curMonth;
for(int i = 0; i<8; i++){
     curMonth = theMonth.AddMonths(-i).ToString("MM/yyyy");
}

which is right or better expression? Or same?

Expert wanna be
  • 10,218
  • 26
  • 105
  • 158

2 Answers2

4

Use

DateTime theMonth = DateTime.Now;
for(int i = 0; i<8; i++){
     string curMonth = theMonth.AddMonths(-i).ToString("MM/yyyy");
}

if you're only going to be using curMonth inside the loop, AND you don't need its value to persist across loop iterations.

Use

DateTime theMonth = DateTime.Now;
string curMonth;
for(int i = 0; i<8; i++){
     curMonth = theMonth.AddMonths(-i).ToString("MM/yyyy");
}

if you're planning on using curMonth after your loop code has finished executing, or you need the value to hold its value between iterations.

Fabian Tamp
  • 4,416
  • 2
  • 26
  • 42
0

@recursive sorry I changed code, my question is, is it OK to define variable in loop?

Of course it is ok to define variables in a loop. Just notice that the content of this variable will be lost everytime the loop reaches the end "}". So your initial question can't be answered here because there is no better expression. It depends on your requirements

Mohnkuchenzentrale
  • 5,745
  • 4
  • 30
  • 41