I have addres book app, and want to write the final result into a text file. I am having hard time to convert my list to an array so that I could execute the WriteAllLines command.
Interface:
abstract class PhoneBookCore {
protected string _group;
public PhoneBookCore(string group) {
this._group=group;
}
public abstract void Add(PhoneBookCore d);
}
class Contect: PhoneBookCore {
private string _firstName;
private string _lastName;
private string _phoneNumber;
private string _addres;
public Contect(string group, string firstName, string lastName, string phoneNumber, string addres)
: base(group) {
this._firstName=firstName;
this._addres=addres;
this._lastName=lastName;
this._phoneNumber=phoneNumber;
}
}
class Group: PhoneBookCore {
private List<PhoneBookCore> elements=new List<PhoneBookCore>();
public List<PhoneBookCore> elementsList {
get;
set;
}
public Group(string name)
: base(name) {
}
public override void Add(PhoneBookCore d) {
elements.Add(d);
}
}
This is where I stuck
class DataOptins {
public string Save(Group g) {
foreach(var item in g) {
string[] arr=g.elementsList.ToArray(); // <---- :(
}
System.IO.File.WriteAllLines(Path, arr); // <---- :(
}
}
Your code is flawed in many ways, but I will focus on your specific question for now.
First, you have to override the
ToString()method in the class Contect:(This is just an example, have your own format of course)
And now have such code to make the list into array of strings:
Now with this and with your current code you will get an exception since
g.elementsListwill always be null. Why? Because you never assign it. Having other private member is all good, but the compiler can’t know that when you call toelementsListyou actually want the private memberelements.Change the code to:
And you won’t have “null exception” anymore. Note that I made the public property return a copy of the list so that the calling code won’t be able to change your private member.