Hi, I'm fairly new to C# so this might be difficult for me to put into words.
I am creating a media application and I have a class (called MediaFile) that contains information about media files (name, size, play count and tags). These are of string, double, int and List<string>
types, respectively.
I have a list of these objects, so for example to call MediaFile[2].Tags
will refer to a list of "tag" strings (related keywords).
The problem I have is that when I ask the user to enter tags for the selected MediaFile, whenever I try to save those tags to that specific object, the tags get saved to every single object. The code for the assignment currently looks something like this:
MediaFile[lstLibrary.SelectedIndices[0]].Tags.Add(tempTag);
'tempTag' is a string that I'm trying to add into the list of strings, but like I said - even though only one file is selected, the 'tempTag' string gets added into the list of strings of each MediaFile.
Can anyone shed some light on what I'm doing wrong?
Many thanks.
EDIT: Thanks for all of your responses. Whenever I create a MediaFile
instance I pass new List<string>
to the constructor. Then later on when I go to change this list of strings I discover all of the MediaFiles seem to have the same string reference. Here is the MediaFile class:
public static List<MediaType> MediaFile = new List<MediaType>();
public class MediaType
{
public string Name;
public string Path;
public double Size;
public int Plays;
public List<string> Tags;
// Constructor for adding new files
public MediaType(string path, List<string> tags)
{
Path = path;
Tags = tags;
}
And after I ask the user to select a file to add to the media library:
MediaFile.Add(new MediaType(Path.GetFullPath(file), new List<string>()));
So there are no 'tags' at first, but then later on (and herein lies my problem):
if (tempTag != "")
MediaFile[lstLibrary.SelectedIndices[0]].Tags.Add(tempTag);
}
Any idea? Apologies this post is so long!