declaring var inside if statement c#

前端 未结 3 1070
遇见更好的自我
遇见更好的自我 2021-01-24 19:11

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

相关标签:
3条回答
  • 2021-01-24 19:35

    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);
    }
    
    0 讨论(0)
  • 2021-01-24 19:35

    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.

    0 讨论(0)
  • 2021-01-24 19:43

    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>).

    0 讨论(0)
提交回复
热议问题