C # Task List <string>
I'm new to C #, so it can be hard for me to put into words.
I am creating a multimedia application, and I have a class (MediaFile) that contains information about media files (name, size, number of games and tags). They are of type string, double, int and List<string>, respectively.
I have a list of these objects, so, for example, to call it MediaFile[2].Tagswill refer to a list of tag lines (related keywords).
The problem is that when I ask the user to enter tags for the selected MediaFile, whenever I try to save these tags to this particular object, the tags are stored in each individual object. The code for the assignment currently looks something like this:
MediaFile[lstLibrary.SelectedIndices[0]].Tags.Add(tempTag);
'tempTag' is the line that I am trying to add to the list of lines, but, as I said, even if only one file is selected, the line "tempTag" is added to the list of lines of each MediaFile.
Can anyone shed light on what I'm doing wrong?
Many thanks.
EDIT: Thanks for all your answers. Whenever I instantiate MediaFile, I pass to the constructor new List<string>. Then later, when I move on to changing this list of strings, I find that all media files seem to have the same string link. 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, at first there are no "tags", but then (and this is my problem):
if (tempTag != "")
MediaFile[lstLibrary.SelectedIndices[0]].Tags.Add(tempTag);
}
Any idea? Sorry this post is so long!
, . , , :
List<string> tags = new List<string>();
MediaFile m1 = new MediaFile();
m1.Tags = tags;
MediaFile m2 = new MediaFile();
m2.Tags = tags;
, Tags MediaFile List<string>. , m1.Tags, m2.Tags.
:
MediaFile m1 = new MediaFile();
m1.Tags = new List<string>();
MediaFile m2 = new MediaFile();
m2.Tags = new List<string>();
Tags set?
, (- )?
var tags = new List<string>();
for (int i = 0; i < MediaFile.Count; ++i)
{
MediaFile[0] = new MediaFile(tags);
}
, MediaFile List<string>.
You should not have an accessory setin this property at all, and the constructor MediaFileshould not accept any external List<string>(unless it copies it). Instead, assign it only in the constructor for MediaFilea new List<string>(); this way you guarantee that each instance gets its own list:
public MediaFile()
{
this.Tags = new List<string>();
}
Or:
public MediaFile(IEnumerable<string> tags)
{
this.Tags = new List<string>(tags);
}