Null-coalescing operator returning null for properties of dynamic objects

This is due to obscure behaviors of Json.NET and the ?? operator. Firstly, when you deserialize JSON to a dynamic object, what is actually returned is a subclass of the Linq-to-JSON type JToken (e.g. JObject or JValue) which has a custom implementation of IDynamicMetaObjectProvider. I.e. dynamic d1 = JsonConvert.DeserializeObject(json); var d2 = JsonConvert.DeserializeObject<JObject>(json); Are actually … Read more

PHP short-ternary (“Elvis”) operator vs null coalescing operator

When your first argument is null, they’re basically the same except that the null coalescing won’t output an E_NOTICE when you have an undefined variable. The PHP 7.0 migration docs has this to say: The null coalescing operator (??) has been added as syntactic sugar for the common case of needing to use a ternary … Read more

Unique ways to use the null coalescing operator [closed]

Well, first of all, it’s much easier to chain than the standard ternary operator: string anybody = parm1 ?? localDefault ?? globalDefault; vs. string anyboby = (parm1 != null) ? parm1 : ((localDefault != null) ? localDefault : globalDefault); It also works well if a null-possible object isn’t a variable: string anybody = Parameters[“Name”] ?? … Read more

C#’s null coalescing operator (??) in PHP

PHP 7 adds the null coalescing operator: // Fetches the value of $_GET[‘user’] and returns ‘nobody’ // if it does not exist. $username = $_GET[‘user’] ?? ‘nobody’; // This is equivalent to: $username = isset($_GET[‘user’]) ? $_GET[‘user’] : ‘nobody’; You could also look at short way of writing PHP’s ternary operator ?: (PHP >=5.3 only) … Read more