Hello,
I’m trying to subtract 3 days from a given date with the following code in a Method Directive
I keep getting the following error
“‘DateTime?’ does not contain a definition for ‘AddDays’ and no accessible extension method ‘AddDays’ accepting a first argument of type ‘DateTime?’ could be found (are you missing a using directive or an assembly reference?)”
Can anyone see the missing rung on the ladder??
var poDueDate = ttpo.DueDate;
var FollowUpDate = poDueDate.AddDays(-3);
Thank you
Now I get this error
“Cannot implicitly convert type ‘System.DateTime?’ to ‘System.DateTime’. An explicit conversion exists (are you missing a cast?)”
If I don’t set a var before that I get this error
“The name ‘poDueDate’ does not exist in the current context”
If I set a var before that I get this error
“‘DateTime?’ does not contain a definition for ‘AddDays’ and no accessible extension method ‘AddDays’ accepting a first argument of type ‘DateTime?’ could be found (are you missing a using directive or an assembly reference?)”
One reason a programmer/designer may use a nullable type because they explicitly want you to handle the null case. Right now your code will throw an exception as you are not handling the case were the date is null.
Actually, that wouldn’t prevent the exception since you are already accessing ttpo.DueDate.Value which is the variable that could be null. You want to be checking if ttpo.DueDate has a value before you try adding to it, or then do something else if its null (such as inform the user or pick a reasonable default value)
also slightly tangential, ever since we upgraded to 10.2.100 I’ve had to go through our bpms and some customizations and change if (something ! = null) into if (something.Any()) as one by one, they’ve thrown a null reference exception the first time they actually hit a situation where something = null.
Apparently the if evaluates the variable and fails before acting on the fact that it’s null.
I usually use the HasValue property on the nullable DateTime because it looks nicer than comparing to null. Both achieve the same result though so it’s really a stylistic choice.
You need it because whatever arguments you pass to the “if” statement must evaluate to true/false. When something is null then the Any() function isn’t called and therefore null is passed to the “if” statement. The compiler will give you an error so comparing null to true is the workaround for the compiler error.
if (something?.Any() == true)
is just a shortcut for
if(something != null && something.Any()).
It doesn’t save you many keystrokes but in my opinion it makes the code a bit more readable and shows the real intent of the “if” statement: that there must be at least one item in the collection to get into that code block.