An old work colleague used to quote his father about tools, "You have to be smarter than it."
In the code below, Resharper is telling me, "Value assigned is not used in any execution path" (pointing to the first line). If I accept its offer of help, dt is not assigned a value ("today").
Is this a case where "I have to be smarter than it" and ignore their warning, or is this a case where the tool is smarter than me, and I'm just not understanding it?
My take on the situation is that if the if statement fails, the current date is returned (the default value I want), but if I acquiesce to Resharper's "demands" it would return the default value for Datetime, which is the minimum date, which I assume is something like 7/4/1776 or 1/1/0000 or so.
DateTime dt = DateTime.Now; if (!(DateTime.TryParse(substr, out dt))) { using (var dtpDlgForm = new ReturnDate("Please select the Date that the file was created:")) { if (dtpDlgForm.ShowDialog() == DialogResult.OK) { dt = dtpDlgForm.ReturnVal; } } } return dt;
The minimum valid date for a SqlDateTime structure is January 1, 1753.
YYYY is four digits from 1753 through 9999 that represent a year. MM is two digits, ranging from 01 to 12, that represent a month in the specified year. DD is two digits, ranging from 01 to 31 depending on the month, that represent a day of the specified month.
This gives a range of 8,640,000,000,000,000 milliseconds to either side of 01 January, 1970 UTC.
The answer you accepted shows what you should be doing but doesn't explain why Resharper complains in the first place. Since this explanation could be useful for others who find your question, here it is:
You should follow Resharper's advice and change the first line to:
DateTime dt;
This declares the variable dt
but does not assign any value to it. There is no need to assign a value here because it will be definitely assigned on the next line due to the out
keyword. From the documentation:
Although variables passed as
out
arguments do not have to be initialized before being passed, the called method is required to assign a value before the method returns.
Emphasis mine. Assigning the value DateTime.Now
is unnecessary and misleading because this value will never be used.
My take on the situation is that if the if statement fails, the current date is returned
That is not what your code does. From the documentation:
result: When this method returns, contains the DateTime value equivalent to the date and time contained in s, if the conversion succeeded, or MinValue if the conversion failed.
With the code you posted if the parse fails then dt
will contain the value DateTime.MinValue
and not the value DateTime.Now
that you assigned.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With