I have 2 classes: Track.cs and TrackList.cs, Track.cs is used to save data from a track. In TrackList I want to save objects of Track.cs in a List.
This is the code i currently have:
class TrackList
{
private List<Tracks> tracks;
public TrackList()
{
tracks = new List<Tracks>();
}
public TrackList(List<Tracks> tracks)
{
this.tracks = new List<Tracks>(tracks);
}
}
What I understand from this is that, When I create an object of this class: TrackList TC = new TrackList() the list will get initialized if I don't add parameters, But when I send a Track.cs object as a parameter it will add to the track list.
But someone said I should use this.tracks = tracks; instead of this.tracks = new List<Tracks>(tracks);. But I don't get why, because if I use this.tracks = tracks; I have not used the = new List<Tracks>; part so it won't be initialized. Or am I thinking incorrectly?
Is it the same as if I do this
int id;
public MyClass()
{
id = 0;
}
public MyClass(int id)
{
this.id = id;
}
Also in my assignment it says the parameter list needs to be assigned to the list in the TrackList class.
Edit 2
My new though after a comment
private List<Tracks> tracks; is a reference to nothing atm.
this.tracks = tracks makes the tracks list ^ reference to the list that was send with parameters
this.tracks = new List<Tracks>(tracks); will create a new list, So the tracks list will now reference that new list, and the new list has the same content as the list that was send with parameters.
So with the method i use(the last one) there are 2 list in existence with the same content but private List<Tracks> tracks; will reference that new list and i dont know what happens to the list that was send with the parameters.
Edit 3
It seems that my assumption in Edit 2 was correct. Thank you guys a lot for your help. Cheers!
public TrackList() : this(new List<Tracks>()) { }. Using chaining prevents bugs from cropping up when you have constructor overloads. The smell for this is that you have multiple constructors instantiating/setting the same fields/properties.tracks = new List<Tracks>();so doesn't that mean it is not initialized? Or does it automatically initialize when I add objects to it?newinitializes an object of a given type. You accept an object of typeList<Tracks>, so whoever news up this instance is the one passing you the object. You can verify it is not null, if you want. I'd strongly suggest you pick up a copy of CLR Via C#. Skip the first two chapters and read. Should take about a day.