Skip to content

Add ToElementOrDefault<T>, which returns null for an element of another type #121

Closed

Description

@Nice3point

Description of the new feature / enhancement

ToElementOrDefault<T> returns the element of the type T with an id, or null for an id of no element or of an element of another type.

ToElement<T> throws InvalidCastException for an element of another type, the way LINQ First throws for an empty sequence.
ToElementOrDefault<T> follows the convention of FirstOrDefault:

var view = elementId.ToElementOrDefault<View>(document);
if (view is null)
{
    return;
}

In the preceding code, view is null when elementId names a wall, and when it names no element of the document.

  • ToElement<T> throws for an element of another type, as it does now.
  • ToElementOrDefault<T> sits beside ToElement<T> in the element id extensions, with the same constraint where T : Element.

Scenario when this would be used?

A tool resolves an id it receives from outside, such as an id a user or another process passes, and treats an id of another element as no match.
Today it writes document.GetElement(elementId) as View in place of the extension.

The agent skill that recommends the extensions changes with it: Nice3point/revit-skills#17.

Activity

  1. self-assigned this
    on Oct 28, 2026
  2. added
    feature request 📬A request for new changes to improve functionality
    revit-api 📡Revit API usage and the supported-version matrix
    on Oct 28, 2026
  3. Nice3point commented on Oct 29, 2026

    @Nice3point
    OwnerAuthor

    Decision

    parameter.AsElementOrDefault<T>() joins the scope: AsElement<T> throws InvalidCastException for an element of another type, the same way ToElement<T> does.

  4. Nice3point commented on Oct 29, 2026

    @Nice3point
    OwnerAuthor

    Decision

    ToElement, ToElement<T>, AsElement, and AsElement<T> throw InvalidOperationException for an id or a parameter that references no element, the way First throws for an empty sequence.
    ToElementOrDefault and AsElementOrDefault, generic and non-generic, return null for it.
    The change is breaking: code that checks the result of ToElement or AsElement for null moves to the OrDefault counterpart.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions