Efficient Array Checks in C# with `Array.TrueForAll()`: A Concise Guide

Learn how to use C#'s `Array.TrueForAll()` method for efficient checks on array elements. This tutorial demonstrates how to apply predicates to verify conditions across all array elements, highlighting the performance benefits of this short-circuiting method.



Using C#'s `Array.TrueForAll()` Method for Efficient Array Checks

The C# `Array.TrueForAll()` method provides a concise and efficient way to check if all elements in an array satisfy a given condition. It's a powerful tool for data validation, filtering, and error detection within arrays.

Understanding `Array.TrueForAll()`

The `Array.TrueForAll()` method applies a specified predicate (a function that returns `true` or `false`) to each element in an array. If the predicate returns `true` for *every* element, `TrueForAll()` returns `true`. If even one element fails the condition, it immediately returns `false` without checking the rest of the array. This short-circuiting behavior is very efficient, especially for large arrays.

`Array.TrueForAll()` Syntax


public static bool TrueForAll<T>(T[] array, Predicate<T> match);

The parameters are:

  • array (T[]): The array to check.
  • match (Predicate<T>): A delegate (or lambda expression) that defines the condition to check for each element. It takes an element as input and returns `true` if the element satisfies the condition; otherwise, `false`.

The return value is a boolean (`true` if all elements satisfy the condition; otherwise, `false`).

Exception Handling

Calling `Array.TrueForAll()` with a `null` array or a `null` predicate throws an `ArgumentNullException`.

Example 1: Checking if All Students are Adults


public class Student {
    public string Name { get; set; }
    public int Age { get; set; }
}

public class Example {
    public static void Main(string[] args) {
        // ... (code to create Student array, define predicate, and use TrueForAll) ...
    }
}

Example 2: Handling `ArgumentNullException`


try {
    bool allAdults = Array.TrueForAll(students, IsAdult); 
} catch (ArgumentNullException ex) {
    Console.WriteLine($"Error: {ex.Message}");
}

Common Use Cases for `Array.TrueForAll()`

  • Data Validation: Check if all elements meet certain criteria.
  • Filtering: Identify elements that satisfy a specific condition.
  • Error Detection: Detect inconsistencies or errors in data.