I have been learning about the collections namespace in C# so have been doing some little self-made projects to learn.
I have made a car race app where you enter in the name, car and place of the racer this is then stored in an array list. I can extract the contents of my array list onto the console window but I would like to know how I can write and save it to a text file (kindof like a mini database).
I know that every element stored in an array list is stored as an object therefore casting is needed to extract them to their appropriate types.
Here is how my array list handles the inputs:
class People
{
private string name;
private string car;
private string place;
public ArrayList myList = new ArrayList();
public string Name
{
get { return name; }
set { name = value; }
}
public string Car
{
get { return car; }
set { car = value; }
}
public string Place
{
get { return place; }
set { place = value; }
}
public void ShowList()
{
for (int i = 0; i < myList.Count; i++)
{
Console.WriteLine("" + myList[i] + "\n|");
}
}
public void AddToList()
{
myList.Add("Name: " + name + " Car: " + car + " Place: " + place);
}
}
Here is how I am trying to save myList to a text file:
private void button3_Click(object sender, EventArgs e)
{
using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\Keil\Documents\Visual Studio 2013\Projects\CarRacingArrList\racers.txt"))
{
file.WriteLine(person.myList.ToString());
}
}
I added the ToString() method to cast all the elements inside myList to a string.
The output I get into my textfile is this: System.Collections.ArrayList
Is the the result of invalid casting or just something I have missed out?
Thankyou