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:
DateTime CurrentDate = DateTime.MaxValue;
DateTime CurrentDate = default(DateTime);
DateTime? CurrentDate = null;
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 .Value
to consider whether or not you have correctly handled the situation where it could be null.
Also: Have you considered that the value of DateTime.Now
could change between the first and second calls? That final if
statement looks like it won't do what you intended.