Krilium Krilium - 2 months ago 9
C# Question

List all class objects

I'm wanting to list all class objects in sort of a list. I have created a bunch of objects with the 'new' tag. It's easier to show you in code so here it is.

static void Main(string[] args)
releaseitem trk1 = new releaseitem("ARTIST", "TRACK 01", "2014");
releaseitem trk2 = new releaseitem("ARTIST", "TRACK 02", "2016");
releaseitem trk3 = new releaseitem("ARTIST", "TRACK 03", "2012");
releaseitem trk4 = new releaseitem("ARTIST", "TRACK 04", "2011");

Console.WriteLine("ID\t\t\tArtist\t\tTitle\t\t\tRelease Year");

You see, at the moment, I have to get the details of each song individually and it shows up like this:

enter image description here

However, I'm soon going to make it so the user can input their own data, and I want to make it so that when the user types "List All", it shows all of the tracks, in a fashion shown in the screenshot. I'll show you what's in the releaseitem class, but I'm not sure if I'll have to change anything there:

public class releaseitem
private string artist = "";
private string title = "";
private string releaseyear = "";
private string id = "";

public releaseitem(string artist, string title, string releaseyear)
this.artist = artist;
this.title = title;
this.releaseyear = releaseyear;
idTracker.nextId += 1;
id = "REL-" + (idTracker.nextId).ToString().PadLeft(4, '0');

public void getDetails()
Console.WriteLine("{0}\t\t{1}\t\t{2}\t\t{3}", id, artist, title, releaseyear);

Ignore the use of 'private', I have no idea on the difference of public and private yet haha.


Have a look at the class List<T> which you can use like this:

releaseitem trk1 = new releaseitem("ARTIST", "TRACK 01", "2014");

var list = new List<releaseitem>();

foreach (var item in list)

Use list.Add to add more items to the list; the foreach-loop will output all of the items you stored so far.