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.
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.
fName.Lengthwill never be 0 because you're declaring it as containing 10 items:static String[] fName = new string[10];Did you actually intend to checkfName[i].LengthlikecNumber[i]?System.NullReferenceExceptionfName[i], then it will be the default value:null. Do you just want to check if it's!= null?fNamecontains at least one item which is not null (nullis the default value if the item is not set yet), so at least item was set to a new value in the array, you could check that with this:bool containsNonNullItem = a.Count(s => s != null) != 0;But if you set a value to null the bool will still say false, even though you set the items value, so it's not a perfect solution.