Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

Enumerable.FirstOrDefault: practical reference

Enumerable.FirstOrDefault: practical reference: Immediately returns the first element or predicate match; when none exists it returns default(T) or an explicitly supplied default value.

Version: .NET LINQ; verified on .NET 10.0.14

Syntax

source.FirstOrDefault(/* overload-specific arguments */)

Immediately returns the first element or predicate match; when none exists it returns default(T) or an explicitly supplied default value.

Use it when absence is normal and the code can represent it unambiguously.

For reference types, null can mean either absence or a real first null element. Use the explicit-default overload or another result model.

An empty source or no match returns default. A null source or predicate still causes ArgumentNullException.

The complete program actually uses Enumerable.FirstOrDefault; its exact expected stdout is 0.

Examples

using System;
using System.Collections.Generic;
using System.Linq;

Console.WriteLine(Array.Empty<int>().FirstOrDefault());

Result

0

The complete program actually uses `Enumerable.FirstOrDefault`; its exact expected stdout is `0`.

Sources