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?
There is no such thing as a default constructor in a
struct. Try it:You can have a static constructor, but you cannot define a default constructor for a
struct. That’s why there’s the static methodCreateon so many structures, and why you can saynew Point()instead ofPoint.Empty.The “default constructor” of any
structalways initializes all of its fields to their default values. TheEmptystatic field of certian types is for convenience. It actually makes zero difference in performance because they’re value types.