I already wrote about the benefits of learning new language features. Equally important is to understand what assemblies are available as part of Dynamics 365 SDK, how they work, what classes and interfaces are available, and how the edge cases work (basically, “what-if” scenarios, like “what if this is null”).
This week I had “privilege” to sink my teeth into some old code written by a developer with a particularly severe case of spießrutenlaufen. My eyes are still bleeding. Consider this fragment:
DateTime? DateAccepted = null; if(entity != null) { DateAccepted = (entity.Contains("new_dateacc") && entity["new_dateacc"] != null && entity["new_dateacc"] != string.Empty) ? entity.GetValue<DateTime>("new_dateacc") : (DateTime?)null; }
I did some line wrapping for your viewing pleasure, original code was a one-liner. At this point in time you should be able to hear my eyes rolling all the way to the back of my head. How about this instead?
var DateAccepted = entity?.GetAttributeValue<DateTime?>("new_dateacc");
There is no magic here, I simply used:
- null conditional operator
- knowledge of the GetAttributeValue method: “When an entity instance does not include the attribute specified using the attributeLogicalName parameter this method will return null rather than throw an exception”
If you are unsure how things would work out if, for example, you used GetAttributeValue<DateTime>
, why don’t you whip out some quick code to test the behavior:
As you can see, return seems to be default(T)
for non-nullable T types. Yep, I’m using the goodness of LINQPad, a must have for every developer.
(Social media cover photo by Easton Oliver on Unsplash)
totally helpful in this case. Not so helpful for int values, when the attribute doesn’t exist or has the value null, 0 will be returned, right?
It’s very much the same for int values:
i will be int?, that is nullable type and will have value of null if attribute is missing.