Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,987 questions

51,931 answers

573 users

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
...