Coalesce operator basic example

There was some null checks for trimming that were added in our codebase like this:

if (model.SearchEmail != null)
    model.SearchEmail = model.SearchEmail.Trim();

A tiny bit “easier”* alternative would be to use the coerce operator:

model.SearchEmail = (model.SearchEmail ?? String.Empty).Trim();

It is a little less typing and a single line. I think it is still pretty obvious what you are trying to do, so if you like it, use it.

If you don’t already know about coalesce, it is basically “if the value is null, use this other value”. So in the above, if model.SearchEmail is null, then use String.Empty. Then, trimming String.Empty would return null. But, if model.SearchEmail has a value, it gets trimmed and everything works as expected.

If you are interested in more examples/info, check out this StackOverflow Q&A.

* I say “easier” because it is my preference for terse yet understandable code. It may not be your preference, and that is cool