Robert W. Hunter
Robert W. Hunter

Reputation: 3003

declaring var inside if statement c#

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 statement is true...

if (DateTime.Today.Day > 28 && DateTime.Today.Day < 2)
{
    var days = GetDaysLikeMe(DateTime.Today).Take(50).Where(d => d.Date.Day > 28 && d.Date.Day < 2).Take(4);
}
else
{
    var days = GetDaysLikeMe(DateTime.Today).Take(50).Where(d => d.Date.Day < 28 && d.Date.Day > 2).Take(4);
}

EDIT:

I've tried to declare the variable outside the box... But can't get it working neither, the function I keep on var days is this

    public IEnumerable<DateTime> GetDaysLikeMe(DateTime currentDate)
    {
        DateTime temp = currentDate;
        while (true)
        {
            temp = temp.AddDays(-7);
            yield return temp;
        }
    }

Upvotes: 1

Views: 12397

Answers (3)

Alexei Levenkov
Alexei Levenkov

Reputation: 100527

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

Upvotes: 1

Greg Smith
Greg Smith

Reputation: 2469

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);
}

Upvotes: 10

Matti Virkkunen
Matti Virkkunen

Reputation: 65126

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.

Upvotes: 3

Related Questions