In your class
Person you have:
Person p = new Person();
This causes endless creation of
Person instances and stack overflow.
Btw. I dont like logical structure of your program. Consider creation of new class
PhoneBook, which operates over collection of Person instances as following:
namespace PhoneBookProject
{
public class PhoneBook
{
List<Person> H = new List<Person>();
private int ID;
public void PrintAll()
{
if (H.Count == 0)
{
Console.WriteLine("Empty.");
return;
}
foreach (Person item in H)
{
Console.WriteLine("First name: {0}", item.FirstName);
Console.WriteLine("Last name: {0}", item.LastName);
Console.WriteLine("Phone number: {0}", item.PhoneNumber);
Console.WriteLine("ID: {0}", item.ID);
}
}
public void AddPerson()
{
Console.WriteLine("Enter first name: ");
string fn = Console.ReadLine();
string FirstName = fn;
Console.WriteLine("Enter last name: ");
string LastName = Console.ReadLine();
Console.WriteLine("Enter phone number: ");
string PhoneNumber = Console.ReadLine();
H.Add(new Person(FirstName, LastName, PhoneNumber, ++ID));
}
public void FindPerson()
{
Console.WriteLine("Please enter first or last name: ");
string search = Console.ReadLine();
foreach (Person item in H)
{
if (search == item.FirstName || search == item.LastName)
{
item.ToString();
Console.WriteLine("*****************");
}
}
}
public void DeletePerson()
{
H.ToString();
Console.WriteLine("Enter an ID to delete: ");
int id = int.Parse(Console.ReadLine());
H.RemoveAt(id);
Console.WriteLine("Person deleted successfully");
}
}
And class Person:
public class Person
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string PhoneNumber { get; set; }
public Person(string fName, string lName, string phoneNum, int id)
{
FirstName = fName;
LastName = lName;
PhoneNumber = phoneNum;
ID = id;
}
public override string ToString()
{
return "First name: " + FirstName + "\n" + "Last name: " + LastName + "\n" + "Phone number: " + PhoneNumber + "\n" + "ID: " + ID + "\n";
}
}
Also modify Menu:
public static void MainStart()
{
string choice = "";
PhoneBook pr = new PhoneBook();
do
{
MainText();
Console.WriteLine("Enter your choice: ");
choice = Console.ReadLine();
switch (choice)
{
case "1":
pr.AddPerson();
break;
case "2":
pr.PrintAll();
break;
case "3":
pr.FindPerson();
break;
case "4":
pr.DeletePerson();
break;
default:
if (choice != "5")
{
Console.WriteLine("Invalid choice. Enter only the above values");
Console.ReadKey();
MainStart();
}
break;
}
Console.WriteLine("Press any key to continue ...");
Console.ReadKey();
Console.Clear();
} while (choice != "5");
}