Array.Trueforall() Method In C#

In this guide, we will explore the Array.TrueForAll method in C# including its syntax, parameters, and sample illustrations.

What is the Array.TrueForAll method?

In C#, the "Array.TrueForAll" static method examines whether every item in an array meets the specified criteria set by a provided predicate. This method iterates through each element in the array, applying the specified predicate function. If all elements meet the specified condition, the method returns true; otherwise, it returns false.

The "Array.TrueForAll" method offers an efficient way to validate each element within an array against a condition by halting the iteration and delivering a false result upon encountering the initial element that fails to meet the specified criteria.

This functionality avoids unnecessary loops and ensures optimal performance, particularly when handling extensive 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 defines a function that sets criteria and evaluates whether the provided object meets those criteria. It takes in a 'T' type parameter and returns a Boolean value indicating if the object meets the specified criteria.

If the conditions specified by the Predicate are met by all items in the Array, the function will yield true. Conversely, if the requirements are not fulfilled, it will yield false. In the case where the Array is empty, the return value will be true.

If the Array or the match happens to be null, this method will raise an ArgumentNullException.

Predicate Delegate

The Predicate serves as a function or lambda expression that takes an array element as an argument and produces a boolean outcome based on whether the element meets the specified criteria.

It empowers users to establish intricate checks based on their individual needs through the flexibility to define conditions in a customizable manner.

Example 1:

Let's consider a scenario to demonstrate how the Array.TrueForAll method is utilized 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 instance, the following code showcases the utilization of the Array class. Employ the TrueForAll function with a predicate to perform a conditional evaluation on elements within an array. The criteria for assessment is whether each individual in the Array is classified as an adult based on their age.

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 scenario, the array of students is empty, leading to the ArgumentNullException being triggered. The following code showcases the appropriate way to manage an exception by employing a try-catch block and displaying the accurate error message.

The function is compatible with any collection type that incorporates the IEnumerable<T> interface, even though its primary design is for arrays.

This flexibility allows for uniformity in coding approaches when dealing with different data arrangements.

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: