
Have you ever been so hyper-focused on something that you overlooked the obvious? Never, right? Well, it happens to me more than I care to admit. One such session recently had me questioning how a line of code could return a null exception when the objects were strings, and inherently nullable. That is, until a coworker pointed out that it wasn’t the string object itself, but what was being done to it. You see, myStringVar.Substring() doesn’t exactly work when myStringVar is null.
Do you believe in coincidences? A few days after my “can’t see the forest for the trees” moment, I was troubleshooting another bit of code that seemed reasonable on the surface but wasn’t. AccessInfo is a pretty widely used object for an Acumatica developer, so it is fairly common to see its use in code. As it happens, AccessInfo doesn’t get common field values set when the graph is running from a business event. I recall having an issue with that regarding Branch ID some time back. Sometimes we need gentle reminders, so here is one… Trying to leverage object extension methods on a null field value in AccessInfo will throw a null exception. The problem here was that the code normally runs from a user session, but when run from a business event, it would fail.
Today’s post is short, but it is very important reminder, especially when someone else will be using your code. Be sure to use proper conditional access operators(?.). Sometimes, a painful problem is a simple as a single keystroke:
If myString can be null, don’t forget the null check. Instead of this:
int? lngth = myString.Length;
Use:
int? lngth = myString?.Length;
Happy coding!