Testtest
Testtest

Reputation: 23

Check if array has no stored value yet

I want to check if my array hasn't stored any data on the array yet then I'll write "No Data Yet" I tried myArray.Length == 0 but it doesn't seem to work.

Result

using System;

namespace IntegMidTerm
{
    class Program
    {
        static String[] fName = new string[10];
        static long[] cNumber = new long[10];
        static String[] numbers = new string[10] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
        static String fullName;
        static int i = 0, k = 0;
        static long contactNumber;

    static void Main(string[] args)
    {
        int optNum;

        while (true)
        {
            Console.WriteLine("\n---Welcome to my C# Phonebook Application---\n");
            Console.WriteLine("\tMain Menu" +
            "\n[1] Create New Contact" +
            "\n[2] View All Contancts" +
            "\n[3] Exit Application\n");

            Console.Write("Enter option number: ");
            optNum = Convert.ToInt32(Console.ReadLine());

            switch (optNum)
            {
                case 1:
                    createContact();
                    break;

                case 2:
                    displayContact();
                    break;

                case 3:
                    Console.WriteLine("Thank you for using my application! Terminating program...");
                    Environment.Exit(0);
                    break;
            }
        }
    }

    public static void createContact()
    {
        Console.Write("\nEnter your full name: ");
        fullName = Console.ReadLine();
        fName[i] = fullName;
        i++;

        Console.Write("\nEnter your contact number: ");
        contactNumber = Convert.ToInt64(Console.ReadLine());
        cNumber[k] = contactNumber;
        k++;
    }

    public static void displayContact()
    {
        if (fName.Length == 0 && cNumber[i] == 0) 
        {
            Console.WriteLine("No Data Yet!");
        }

        for (int j = 0; j < numbers.Length; j++)
        {
            Console.WriteLine(numbers[j] + ". " + fName[i] + " - " + cNumber[k]);
        }
    }
}
}

The above result I've shown is somewhat wrong it is because I haven't created new contact yet, then I press number 2 which will show the data stored but since I use if statement which is if array is empty or no data stored yet "No Data yet" will show. but in my case it shows the data.

Upvotes: 1

Views: 102

Answers (1)

Hita Barasm
Hita Barasm

Reputation: 49

As you are using arrays, when an array is being initialized, its length will be constant. In your case, fName and cNumber will have a length of 10 always. If you would like to have dynamic length including zero, use List in C#. Like this:

static List<string> fName = new List<string>();
if (fName.Count == 0)
{
  // do something
}
// to add an item to list you can do:
fName.Add("john");

Upvotes: 3

Related Questions