In the following code snippet, if I leave out the line of code that is surrounded by the /////’s, I get an error that reads: “Use of unassigned local variable CurrentDate”. It seems a bit silly for me to just give CurrentDate an arbitrary value, is there a better way around this?
DateTime CurrentDate;
///////////////////////////
CurrentDate = DateTime.Now;
///////////////////////////
if(1==1)
{
CurrentDate = DateTime.Now.AddDays(1);
}
if(CurrentDate == DateTime.Now)
{
...
}
Don’t do
if (1 == 1)?Seriously though if the compiler is giving you this error it’s usually either because your code is wrong or it’s because it’s too complex and could be better expressed in another way where you don’t need to access possibly unassigned variables.
Can you come up with a real world example where you get this error where there isn’t an obvious solution by making a simple refactoring? This would make your question more answerable.
Having said that if you do run into one of these situations there are a few other approaches you could use:
I like the last option because it expresses what you mean – that you don’t know the value. It makes the code a little more verbose though as you have an extra level of redirection every time you wish to access a value. You can use the time spent typing
.Valueto consider whether or not you have correctly handled the situation where it could be null.Also: Have you considered that the value of
DateTime.Nowcould change between the first and second calls? That finalifstatement looks like it won’t do what you intended.