dotnet/wpf · error · ArgumentException
SR.Collection_NoNull
Error message
SR.Collection_NoNull
What it means
UIElementCollection.Cast (used by Add, Insert and the constructor's IList paths) throws ArgumentException when a null value is supplied, because the collection does not permit null children. The message names SR.Collection_NoNull with the collection type.
Solutions
- Null-check the element before adding it to the collection.
- Fix the factory/loader that returned null instead of a UIElement.
- Use Children.Remove on placeholder elements rather than adding nulls.
Example fix
// before panel.Children.Add(BuildElement()); // may return null // after var e = BuildElement(); if (e != null) panel.Children.Add(e);
Defensive patterns
Strategy: validation
Validate before calling
if (element != null) panel.Children.Add(element);
Type guard
static bool IsAddable(UIElement e) => e != null;
Try / catch
try { panel.Children.Add(value); }
catch (ArgumentException ex) { /* null or wrong type; log and skip */ } Prevention
- Null-check factory results before adding to Children.
- Fail fast in loaders that produce null elements.
- Use Remove instead of adding nulls to clear items.
When it happens
Trigger: panel.Children.Add(null), panel.Children.Insert(0, null), or adding through an IList reference where the item is null.
Common situations: Data binding or factory methods that can return null; building UI from deserialized models where an element failed to instantiate; loop-generated children where a creation step returned null.
Related errors
- SR.Collection_BadType
- ArgumentOutOfRangeException (timeout was Duration.Automatic)
- Buffer address passed to GetText cannot be NULL.
- Collection_BadRank
- Collection_CopyTo_ArrayCannotBeMultidimensional
AI-assisted analysis of dotnet/wpf@81131a70a4 (2026-09-14).
Data as JSON: /api/errors/2f0e6fe583d7dcee.
Report an issue: GitHub.
Appendix: source
Thrown at src/Microsoft.DotNet.Wpf/src/PresentationFramework/System/Windows/Controls/UIElementCollection.cs:386
_visualParent.InvalidateMeasure();
}
}
/// <summary>
/// Method that forwards to VisualCollection.Move
/// </summary>
/// <param name="visual"></param>
/// <param name="destination"></param>
internal void MoveVisualChild(Visual visual, Visual destination)
{
_visualChildren.Move(visual, destination);
}
private UIElement Cast(object value)
{
if (value == null)
throw new System.ArgumentException(SR.Format(SR.Collection_NoNull, "UIElementCollection"));
UIElement element = value as UIElement;
if (element == null)
throw new System.ArgumentException(SR.Format(SR.Collection_BadType, "UIElementCollection", value.GetType().Name, "UIElement"));
return element;
}
#region IList Members
/// <summary>
/// Adds an element to the UIElementCollection
/// </summary>
int IList.Add(object value)
{
return Add(Cast(value));
}View on GitHub (pinned to 81131a70a4)