U4-6986 - PublishedContentExtensions.FirstChild() throws exception

Created by Lee Kelleher 19 Aug 2015, 12:46:06 Updated by Shannon Deminick 19 Aug 2015, 13:42:13

Relates to: U4-6354

TL;DR; When calling FirstChild() when the node has no children will throw an "Sequence contains no elements" exception.

Take this code snippet...

var firstChild = Model.Content.FirstChild(); if (firstChild != null) { // do something }

When there are child nodes, this code is fine. When there are no child nodes, it throws the "Sequence contains no elements" exception.

However change the code to use one of the other FirstChild overloads, then it will not throw an exception and return a null value.

// The FirstChild<T>(this IPublishedContent content) overload var firstChild = Model.Content.FirstChild();

// The FirstChild(this IPublishedContent content, Func<IPublishedContent, bool> predicate) overload var firstChild = Model.Content.FirstChild((x) => { return true; });

The reason for this is that the parameter-less FirstChild() is returning .First() and the others are returning .FirstOrDefault().

Personally, I'd say that returning .FirstOrDefault() is preferable... would there be any reason not to do this?

I can provide a PR + unit-test.

This may be related to #U4-6354?


Lee Kelleher 19 Aug 2015, 12:59:08

PR submitted: https://github.com/umbraco/Umbraco-CMS/pull/767

Priority: Normal

Type: Bug

State: Fixed


Difficulty: Normal


Backwards Compatible: True

Fix Submitted: Pull request

Affected versions:

Due in version: 7.3.0


Story Points: