How to check in array argument send to method is empty in C#

1 Answer

0 votes
using System;

class Program
{
    private static void DisplayArray(string[] arr) {
        string s = arr.Length >= 1 ? arr[0] : throw new ArgumentException("Array is empty");
        
        Console.WriteLine(s);
    }
    static void Main() {
        string[] arr1 = {"c#", "vb.net", "c++"};
        DisplayArray(arr1);
        
        string[] arr2 = {};
        DisplayArray(arr2);
    }
}



/*
run:

c#


Unhandled Exception:
System.ArgumentException: Array is empty
  at Program.DisplayArray (System.String[] arr) [0x00011] in <974078c8db4b4b3f96419a60f7851d55>:0 
  at Program.Main () [0x0002b] in <974078c8db4b4b3f96419a60f7851d55>:0 
[ERROR] FATAL UNHANDLED EXCEPTION: System.ArgumentException: Array is empty
  at Program.DisplayArray (System.String[] arr) [0x00011] in <974078c8db4b4b3f96419a60f7851d55>:0 
  at Program.Main () [0x0002b] in <974078c8db4b4b3f96419a60f7851d55>:0 

*/

 



answered Nov 28, 2020 by avibootz
...