Array.Trueforall() Method In C#

In this article, we will discuss the Array.TrueForAll method in C# with its syntax, parameters, and examples.

What is the Array.TrueForAll method?

In C#, the "Array.TrueForAll" static method checks if each element in an array satisfies the requirements given by a given predicate. It applies the designated predicate function to each element in the Array; if every element satisfies the condition, it returns true; if not, it returns false.

The "Array.TrueForAll" method provides an effective approach to check every element of an array for a condition because it stops iterating and returns false as soon as it reaches the first element that does not fulfil the requirement.

This behaviour prevents needless iterations and guarantees excellent performance, especially for large arrays.

Syntax:

It has the following syntax:

Example

public static bool TrueForAll<T>(T[] array, Predicate<T> match);
  • T: T is the type of element of the Array.
  • array: It is the zero-based one-dimensional Array that will be searched.
  • match: The Predicate delegate that establishes the requirements for comparing the elements.

The Predicate<T> delegate describes a procedure that establishes requirements and determines if the given object satisfies them. It accepts a single parameter of type 'T' and yields a Boolean value that indicates whether or not the object satisfies the requirements specified by the method.

Return Value: If all elements in the Array satisfy the Predicate's given requirements, the procedure returns true; if not, it returns false. The return value is true if there are no elements in the Array.

Exception: If the Array or the match is null, this method raises ArgumentNullException.

Predicate Delegate

The Predicate is a method or lambda expression that accepts an array element as a parameter and returns a boolean value depending on whether the element satisfies the given condition.

It enables users to define complex checks depending on their unique requirements by allowing for flexible condition definitions.

Example 1:

Let us take an example to illustrate the use of the Array.TrueForAll method in C#.

Example

using System;
class Student
{
    public string student_Name { get; set; }
    public int student_Age { get; set; }
    public Student(string student_name, int student_age)
    {
        student_Name = student_name;
        student_Age = student_age;
    }
}
class Demo
{
    static void Main()
    {
        // Create an array of Student objects.
        Student[] students = {
            new Student("Thomas", 28),
            new Student("Peter", 18),
            new Student("Joseph", 22),
            new Student("Issac", 20)
        };
        //Predicate that determines if a student is an adult (those who are at least 18 years old)
        Predicate<Student> is_Adult = (Student student) => student.student_Age >= 18;
        // Verifying that every student in the Array is an adult.
        bool Adults = Array.TrueForAll(students, is_Adult);
        if (Adults)
        {
            Console.WriteLine("All students are adults.");
        }
        else
        {
            Console.WriteLine("Not all students are adults.");
        }
    }
}

Output:

Output

All students are adults.

Explanation:

In this example, this code demonstrates the use of the Array. Use the TrueForAll method with a predicate to do a conditional check on elements in an array. Their ages specifically determine if each student in the Array is an adult.

1. For ArgumentNullException

Example

using System;
class Demo
{
    static void Main()
    {
        // Create an array of Student objects.
        Student[] students = null;
        //Predicate that determines if a student is an adult (those who are at least 18 years old)
        Predicate<Student> is_Adult = (Student student) => student.student_Age >= 18;
        try
        {
            // Verifying that every student in the Array is an adult.
            bool Adults = Array.TrueForAll(students, is_Adult);
            if (Adults)
            {
                Console.WriteLine("All students are adults.");
            }
            else
            {
                Console.WriteLine("Not all students are adults.");
            }
        }
        catch (ArgumentNullException e)
        {
            Console.WriteLine($"An ArgumentNullException occurred: {e.Message}");
            // Handle the exception here, such as logging or displaying an error message.
        }
    }
}
class Student
{
    public string student_Name { get; set; }
    public int student_Age { get; set; }
    public Student(string student_name, int student_age)
    {
        student_Name = student_name;
        student_Age = student_age;
    }
}

Output:

Output

An ArgumentNullException occurred: Value cannot be null.
Parameter name: Array

Explanation:

In this case, the students array is null, which causes the ArgumentNullException to be raised. The code demonstrates how to handle an exception gracefully using a try-catch block and the proper error message printed.

The method works with any collection type that implements the IEnumerable<T> interface, although it is specifically meant to be used with arrays.

This versatility enables consistency in programming methods when working with various data structures.

Common Use Cases

There are several use cases of the Array.TrueForAll method in C#. Some main use cases of the Array.TrueForAll method are as follows:

  • Data validation: Before processing further, data in an array might be checked against predetermined criteria.
  • Filtering: It can filter out elements that do not meet certain conditions, helping to streamline data processing pipelines.
  • Error checking: Data structures represented by arrays that can be examined for errors or inconsistent data.

Input Required

This code uses input(). Please provide values below: