dotnet/maui · error · ArgumentNullException

internal ElementTemplate(Func<object> loadTemplate) : this()

Error message

internal ElementTemplate(Func<object> loadTemplate) : this() => LoadTemplate = loadTemplate ?? throw new ArgumentNullException(nameof(loadTemplate));

What it means

Thrown by the ElementTemplate(Func<object>) constructor when the loadTemplate delegate is null. This constructor assigns the delegate directly to the public LoadTemplate property, which is later invoked to create content (for DataTemplate/ControlTemplate). A null delegate cannot produce instances, so it is rejected.

Source

Thrown at src/Controls/src/Core/ElementTemplate.cs:36

		internal ElementTemplate()
		{
		}

		internal ElementTemplate(
			[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type type)
			: this()
		{
			if (type == null)
				throw new ArgumentNullException(nameof(type));

			_canRecycle = true;
			_type = type;

			LoadTemplate = () => Activator.CreateInstance(type);
		}

		internal ElementTemplate(Func<object> loadTemplate) : this() => LoadTemplate = loadTemplate ?? throw new ArgumentNullException(nameof(loadTemplate));

		public Func<object> LoadTemplate { get; set; }

		void IElementDefinition.AddResourcesChangedListener(Action<object, ResourcesChangedEventArgs> onchanged)
		{
			_changeHandlers = _changeHandlers ?? new List<Action<object, ResourcesChangedEventArgs>>(1);
			_changeHandlers.Add(onchanged);
		}

		internal bool CanRecycle => _canRecycle;

		[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)]
		internal Type Type => _type;

		Element IElementDefinition.Parent
		{
			get { return _parent; }
			set

View on GitHub (pinned to f377ff1c5e)

Solutions

  1. Pass a non-null Func<object> that returns a valid element instance.
  2. Null-check the delegate before constructing the template.
  3. Provide a fallback factory for the null case.

Example fix

// before
var template = new DataTemplate(MaybeNullFactory); // throws if factory is null
// after
Func<object> factory = MaybeNullFactory ?? (() => new DefaultView());
var template = new DataTemplate(factory);
Defensive patterns

Strategy: validation

Validate before calling

if (loadTemplate == null) throw new ArgumentNullException(nameof(loadTemplate));
var template = new DataTemplate(loadTemplate);

Prevention

When it happens

Trigger: Constructing new DataTemplate((Func<object>)null) or new ControlTemplate((Func<object>)null). Happens when a factory method returns null or when a lambda is conditionally assigned and the null path is passed.

Common situations: Programmatic template creation where the factory expression evaluates to null; refactoring a lambda out into a variable that is null; conditional template selection passing null in a branch.

Related errors


AI-assisted analysis of dotnet/maui@f377ff1c5e (2026-08-13). Data as JSON: /api/errors/25d946acbde315f6. Report an issue: GitHub.