I have this var, but I want to change it\'s content depending on the statement, I can\'t get it working because when I use it, VS says it has not been declared, even if the stat
Declare the variable outside the scope of the if statement:
IEnumerable<DateTime> days;
if (DateTime.Today.Day > 28 && DateTime.Today.Day < 2)
{
days = GetDaysLikeMe(calendario.Value.Date).Take(50).Where(d => d.Date.Day > 28 && d.Date.Day < 2).Take(4);
}
else
{
days = GetDaysLikeMe(calendario.Value.Date).Take(50).Where(d => d.Date.Day < 28 && d.Date.Day > 2).Take(4);
}
Declare the variable outside the if block (without assigning a value - you can't use var
in this case though, you'll have to specify the type), and then only assign a value to it inside.
There is nothing wrong with your code as it is now - you can easily define varables with var
or explicitly specifying type inside any block, including if
.
What likely happens is that you are trying to use this varable outside the block it is defined (i.e. after if
statement) which is where days
becomes undefined.
Fix: define variable outside the if, but you need explicit type there. If you have ReSharper it allows easily change between var
/explicit type. Otherwise you'll have to figure out type yourself (in your case it is liklye IEnumerable<DateTime>
).