Skip to content

FirstOrDefault throws IndexOutOfRangeException randomly #3704

@NoxFly

Description

@NoxFly

What happened?

Sometimes, and regularly, doing FirstOrDefault() with or without a predicate throws an exception :

Image

In the same project, this never happened before for the same code which didn't changed, then it started to happen while all nuget packages remain the same with the same version.

It happens on some FirstOrDefault, but not every FirstOrDefault.

Realm .NET 20.0.0 | Realm Studio 15.2.1

This is the same issue as [Bug]: After GetInstance, calling All().FirstOrDefault(); throws System.ArgumentOutOfRangeException #3092

This issue was closed really fastly on 2022 just because couldn't reproduce, but there's still this issue in 2025.

UWP project, C# 7.3

Repro steps

I suspect maybe from one of these 3 things :

  • something from having multiple realm instances,
  • instanciating it too fast, and doing a request too fast after GetInstance, or something similar, because this wasn't happening before, when using a single instance for the whole app.
  • Trying to access a property from a realm object inside the predicate clause. See example just below :
// maybe this could cause an issue
var person = realm.All<Person>().FirstOrDefault(p => p.No == selectedPerson.No);

// Maybe this is a tmp fix
var pno = selectedPerson.No;
var person = realm.All<Person>().FirstOrDefault(p => p.No = pno);

I didn't capture the stacktrace but when inspecting it, a line was on a getter of the property No of the Person realm object class (don't know which one of the two).
However, this is throwing even if this is a a query like this : realm.All<T>().Where(predicate).FirstOrDefault();.

Version

20.0.0

What Atlas Services are you using?

Local Database only

What type of application is this?

Other

Client OS and version

Windows 11 24H2

Code snippets

Can't really understand which .FirstOrDefault() or .FirstOrDefault(predicate) throws or not. The same instruction won't throw for months and suddenly throw.

Stacktrace of the exception/crash you're getting

Relevant log output

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions