Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Use of unassigned variable" -- work arounds?

Now I've long known and been use to this behavior in C#, and in general, I like it. But sometimes the compiler just isn't smart enough.

I have a small piece of code where right now my workaround isn't a big problem, but it could be in similar cases.

        bool gap=false;
        DateTime start; // = new DateTime();
        for (int i = 0; i < totaldays; i++)
        {
            if (gap)
            {
                if (list[i])
                {
                    var whgap = new WorkHistoryGap();
                    whgap.From = start; //unassigned variable error
                    whgap.To = dtFrom.AddDays(i);
                    return whgap;
                }
            }
            else
            {
                gap = true;
                start = dtFrom.AddDays(i);
            }
        }

The problem I'm seeing is what if you had to do this with a non-nullable struct that didn't have a default constructor? Would there be anyway to workaround this if start wasn't a simple DateTime object?

like image 676
Earlz Avatar asked Nov 28 '22 10:11

Earlz


2 Answers

The compiler has no way of knowing that you are guaranteed to set DateTime because of your gap variable.

Just use

DateTime start = DateTime.Now;

and be done with it.

Edit Better yet, on second glance through your code, use

DateTime start = dtFrom;
like image 35
Randolpho Avatar answered Dec 09 '22 08:12

Randolpho


sometimes the compiler just isn't smart enough

The problem you want the compiler to solve is equivalent to the Halting Problem. Since that problem is provably not solvable by computer programs, we make only a minimal attempt to solve it. We don't do anything particularly sophisticated. You're just going to have to live with it.

For more information on why program analysis is equivalent to the Halting Problem, see my article on the subject of deducing whether the end point of a method is reachable. This is essentially the same problem as determining if a variable is definitely assigned; the analysis is very similar.

http://blogs.msdn.com/b/ericlippert/archive/2011/02/24/never-say-never-part-two.aspx

what if you had to do this with a non-nullable struct that didn't have a default constructor?

There is no such animal. All structs, nullable or otherwise, have a default constructor.

Would there be anyway to workaround this if start wasn't a simple DateTime object?

The expression default(T) gives you the default value for any type T. You can always say

Foo f = default(Foo);

and have a legal assignment. If Foo is a value type then it calls the default constructor, which always exists. If it is a reference type then you get null.

like image 188
Eric Lippert Avatar answered Dec 09 '22 07:12

Eric Lippert