0
0
CsharpHow-ToBeginner · 3 min read

How to Find Max in Array in C# - Simple Guide

To find the maximum value in an array in C#, use the Max() method from System.Linq. For example, int max = array.Max(); returns the largest number in the array.
📐

Syntax

The syntax to find the maximum value in an array uses the Max() method from the System.Linq namespace.

  • array.Max(): Returns the largest element in the array.
  • You must include using System.Linq; at the top of your file.
csharp
using System.Linq;

int max = array.Max();
💻

Example

This example shows how to find the maximum number in an integer array using Max(). It prints the largest value to the console.

csharp
using System;
using System.Linq;

class Program
{
    static void Main()
    {
        int[] numbers = { 5, 12, 3, 21, 8 };
        int max = numbers.Max();
        Console.WriteLine("The maximum value is: " + max);
    }
}
Output
The maximum value is: 21
⚠️

Common Pitfalls

Common mistakes when finding the max in an array include:

  • Not including using System.Linq;, which causes Max() to be undefined.
  • Calling Max() on an empty array, which throws an InvalidOperationException.
  • Trying to find max on a null array, which causes a NullReferenceException.

Always check that the array is not empty or null before calling Max().

csharp
using System;
using System.Linq;

class Program
{
    static void Main()
    {
        int[] emptyArray = {};

        // Wrong: This will throw InvalidOperationException
        // int max = emptyArray.Max();

        // Right: Check if array has elements
        if (emptyArray.Length > 0)
        {
            int max = emptyArray.Max();
            Console.WriteLine(max);
        }
        else
        {
            Console.WriteLine("Array is empty.");
        }
    }
}
Output
Array is empty.
📊

Quick Reference

Summary tips for finding max in array:

  • Use array.Max() from System.Linq.
  • Always include using System.Linq;.
  • Check array is not empty or null before calling Max().
  • Works with arrays of numbers and other comparable types.

Key Takeaways

Use Max() from System.Linq to find the largest value in an array.
Always add using System.Linq; to access Max().
Check that the array is not empty or null before calling Max() to avoid errors.
The Max() method works with any array of comparable types, not just integers.