I am having trouble with a homework assignment, were we are supposed to make a phonebook. The condition is that it is supposed to look like this:
Class Phonebook
{
private List<Entry> _phoneList;
public Phonebook()
{
//instance of _phoneList
}
public void AddEntry (string name, string number)
{
//logic
}
public string FindEntry (string namne)
{
//logic
}
}
class Entry
{
public string Name{ get; private set; }
public string Number{ get; private set; }
}
However, I am not certain in how to make the AddEntry method assign new names/numbers to Entry list _phoneList. I have tried a lot, but to no avail. Any hints how to make it work? Any help would be much appreciated!
My code thus far looks like this
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace app3
{
public partial class Form1 : Form
{
private Phonebook phonebook;
public Form1()
{
InitializeComponent();
phonebook = new Phonebook();
}
private void addEntryButton_Click(object sender, EventArgs e)
{
phonebook.AddEntry((addNameTextBox.Text), (addNumberTextBox.Text));
}
}
class Phonebook
{
private List<Entry> _phoneList;
public Phonebook()
{
List<Entry> _phoneList = new List<Entry>();
}
public void AddEntry(string name, string number)
{
}
}
class Entry
{
public string Name { get; private set; }
public string Number { get; private set; }
}
}
Since
_phoneListis a collection ofEntry‘s, you need to create a new instance and add it to the list.However since Entry has private setters for the properties, you should add a new constructor taking in the name and number and set it there instead.
and then it would simply become
Edit:
You declare _phoneList as a private field, but then you re-declare it in your constructor which hides the original.
When you later use
_phoneListin your AddEntry method, you’re getting the uninitialized field. Change the constructor to