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!
That suggests you've added the same string reference to all the MediaFiles. In other words, you might have done:
List<string> tags = new List<string>();
for (int i = 0; i < 100; i++)
{
MediaFile file = new MediaFile(tags);
MediaFiles.Add(file);
}
This is very easy to test - just check whether MediaFile[0].Tags == MediaFile[1].Tags - I suspect you'll find that evaluates to True, meaning you're using the same list for both files.
Instead, you should create a new List<string> for each MediaFile instance.
If you could post some code, that would help us to pin down the problem more precisely, of course...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With