Developer 101: Beware of optional parameters in Custom Actions

Today I was testing a custom action that I developed for a project I’m working on. The plugin registered on the action was not behaving as expected. It was time for some thorough investigation.

The custom action I defined in CRM had a large set of input and output parameters. A large number of the input parameters were optional.

Customaction

Among the optional parameters there were reference variables (Picklist, String, EntityReference) and primitive variables (int, decimal, DateTime).

In order to test my action, I wrote a sample program in which I set the required parameters only. I omitted the optional parameters.
The plugin logic behind the action was designed to work around missing values.

Actiontester

When running the test program, I set a breakpoint to inspect the incoming action parameters and then I noticed a behaviour I didn’t expect.

Actionparameters

The DiscountOrMarkupPercentage, Quantity and EndDate parameters which I didn’t specify in the action call, contained default values. They were supposed to be NULL.

I didn’t see this coming!

Especially not when I defined the specific parameters to be optional. The other parameters which I didn’t specify were NULL.

As a developer with a C background I understand the different behaviour in the omitted parameters.

Do I think it is logical towards the developer? Nope!

In my opinion Microsoft should have implemented this behaviour differently. Once specified optional, an integer, decimal or DateTime should be considered a nullable integer, a nullable decimal or a nullable DateTime.

I hope this behaviour will be fixed some day.  Till that day comes, please beware of optional parameters!

2 thoughts on “Developer 101: Beware of optional parameters in Custom Actions

  1. Si Purdy says:

    It does make sense, Integer Decimal and DateTime are all value types, so will always have a value. But you’re right that the CRM platform ideally would detect the value types and impement them as nullable.

    • From a developer’s perspective it makes sense. However, if I have the option to pass in parameters optionally, I do expect them to be null if not specified. Especially since .NET supports the nullable types (int?, decimal?, DateTime? etc)

      Bas

Leave a Reply

Your email address will not be published. Required fields are marked *