Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Giacomo Lanza 8 posts 77 karma points
    Feb 10, 2023 @ 08:55
    Giacomo Lanza
    0

    Children<T>() never returns null

    Hi everyone!

    I was wondering why this piece of code:

    IEnumerable<Activity>? activities = Umbraco.AssignedContentItem.Children<Activity>();
    

    doesn't returns null when there are no children. It returns always an empty collection so why Children() has nullable returning type?

    Can I safely use this code:

    IEnumerable<Activity> activities = Umbraco.AssignedContentItem.Children<Activity>()!;
    

    Thanks!

  • Roy Berris 89 posts 577 karma points c-trib
    Feb 10, 2023 @ 13:35
    Roy Berris
    0

    Hi,

    What version of Umbraco are you using? I am going with Umbraco 10 for now.

    Looking at the source code from V10 this can return null. The method is marked as IEnumerable<IPublishedContent>?.

    You should check for null, a easy way of doing it is like this:

    if (Umbraco.AssignedContentItem.Children<Activity>() is IEnumerable<Activity> children)
    {
         // do whatever with 'children'
    }
    
  • Roy Berris 89 posts 577 karma points c-trib
    Feb 10, 2023 @ 13:45
    Roy Berris
    0

    Your question got me curious. I was wondering why null was appropriate here. Turns out this got changed in V11, it will now guarantee an empty enumerable instead of null.

    Good to know is that just to be safe I would still do the null check in V10 even though they can get a bit annoying.

  • Giacomo Lanza 8 posts 77 karma points
    Feb 21, 2023 @ 08:07
    Giacomo Lanza
    0

    Hi Rob,

    I'm using Umbraco version 10.4.0.

    Good to know that in V11 the empty enumerable is guaranteed and in my opinion this is the right choice instead of returning null.

    The reason why the method can return null is not clear to me, but so far I have never run into a case where it returns null, this is the only thing I can report.

    In addition to that, I can say that there are also other methods/properties which behave in the same way such as the Multiple Image Picker: it always returns an empty list even if no image has been selected.

    Does it make sense for this properties to check for null even though I'm sure it will never be returned? Isn't it better to use the null-forgiving operator (!) to make the code cleaner and avoid unnecessary checks?

Please Sign in or register to post replies

Write your reply to:

Draft