{"record":{"id":"659a93fa2edaae8c","repo":"TheAlgorithms/C-Sharp","slug":"array-cannot-be-null-or-empty","errorCode":null,"errorMessage":"Array cannot be null or empty.","messagePattern":"Array cannot be null or empty\\.","errorType":"exception","errorClass":"ArgumentException","httpStatus":null,"severity":"error","filePath":"Algorithms/Other/KadanesAlgorithm.cs","lineNumber":30,"sourceCode":"    ///     Finds the maximum sum of a contiguous subarray using Kadane's Algorithm.\n    ///     The algorithm works by maintaining two variables:\n    ///     - maxSoFar: The maximum sum found so far (global maximum)\n    ///     - maxEndingHere: The maximum sum of subarray ending at current position (local maximum)\n    ///     At each position, we decide whether to extend the existing subarray or start a new one.\n    /// </summary>\n    /// <param name=\"array\">The input array of integers.</param>\n    /// <returns>The maximum sum of a contiguous subarray.</returns>\n    /// <exception cref=\"ArgumentException\">Thrown when the input array is null or empty.</exception>\n    /// <example>\n    ///     Input: [-2, 1, -3, 4, -1, 2, 1, -5, 4].\n    ///     Output: 6 (subarray [4, -1, 2, 1]).\n    /// </example>\n    public static int FindMaximumSubarraySum(int[] array)\n    {\n        // Validate input to ensure array is not null or empty\n        if (array == null || array.Length == 0)\n        {\n            throw new ArgumentException(\"Array cannot be null or empty.\", nameof(array));\n        }\n\n        // Initialize both variables with the first element\n        // maxSoFar tracks the best sum we've seen across all subarrays\n        int maxSoFar = array[0];\n\n        // maxEndingHere tracks the best sum ending at the current position\n        int maxEndingHere = array[0];\n\n        // Iterate through the array starting from the second element\n        for (int i = 1; i < array.Length; i++)\n        {\n            // Key decision: Either extend the current subarray or start fresh\n            // If adding current element to existing sum is worse than the element alone,\n            // it's better to start a new subarray from current element\n            maxEndingHere = Math.Max(array[i], maxEndingHere + array[i]);\n\n            // Update the global maximum if current subarray sum is better","sourceCodeStart":12,"sourceCodeEnd":48,"githubUrl":"https://github.com/TheAlgorithms/C-Sharp/blob/96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c/Algorithms/Other/KadanesAlgorithm.cs#L12-L48","documentation":"Kadane's algorithm needs at least one element because the maximum subarray is initialized from array[0]; a null or empty array has no valid answer, so FindMaximumSubarraySum(int[]) throws ArgumentException with parameter name 'array'.","triggerScenarios":"Calling FindMaximumSubarraySum(null) or with an empty int[] from an empty dataset, empty file read, or a filter that removed all values.","commonSituations":"Aggregating profit/temperature series over an empty period; CSV/JSON inputs with no rows; unit tests passing empty arrays to check edge behavior.","solutions":["Check array is non-null and Length > 0 before calling and decide the empty answer (0, NaN, or error) at the call site","Fix upstream data loading so empty datasets are handled before analysis","Catch ArgumentException and map it to an empty-input business rule"],"exampleFix":"// before\nvar max = KadanesAlgorithm.FindMaximumSubarraySum(values);\n// after\nvar max = values is { Length: > 0 } ? KadanesAlgorithm.FindMaximumSubarraySum(values) : 0;","handlingStrategy":"validation","validationCode":"if (array is null || array.Length == 0) return 0; // or your empty-input convention","typeGuard":"static bool IsNonEmpty(int[]? a) => a is { Length: > 0 };","tryCatchPattern":"try { return KadanesAlgorithm.FindMaximumSubarraySum(array); }\ncatch (ArgumentException ex) when (ex.ParamName == \"array\") { return 0; }","preventionTips":["Decide a documented empty-input result (0 or error) and enforce it before calling","Never pass unloaded/failed dataset arrays straight into analysis","Add unit tests for null/empty edge cases"],"tags":["empty-array","null-check","algorithms"],"backgroundTag":"empty-required-field","analyzedSha":"96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c","analyzedAt":"2026-09-13T17:04:01.438Z","contentChangedAt":"2026-09-13T17:04:01.438Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}