Reputation: 1
I need to fill a list of:
public class Photo
{
public string PicturePath { get; set; }
public string ThumbPath { get; set; }
public string Description { get; set; }
}
List<Photo> photoList = new List<Photo>();
this code fails at photoList[z].PicturePath for z = 0
, the value of _PicturePath is a valid path:
for (int z = 0; z < xTotalNbrShown; z++)
{
photoList[z].PicturePath = _PicturePath;
photoList[z].ThumbPath = _ThumbPath;
photoList[z].Description = MakeALT(FileName);
}
"Index was out of range. Must be non-negative and less than the size of the collection.\r\nParameter name: index"
Upvotes: -1
Views: 89
Reputation: 726849
List<Photo> photoList = new List<Photo>();
creates an empty list. Therefore,
photoList[z].PicturePath = _PicturePath;
will fail for all values of i
, because the index would be out of valid range. Instead, create Photo
object, and add it to the list, like this:
for (int z = 0; z < xTotalNbrShown; z++)
{
Photo p = new Photo();
p.PicturePath = _PicturePath;
p.ThumbPath = _ThumbPath;
p.Description = MakeALT(FileName);
photoList.Add(p);
}
Instead of setting the attributes of the instance of Photo one at a time, you could use an object initializer instead:
for (int z = 0; z < xTotalNbrShown; z++)
{
Photo p = new Photo
{
PicturePath = _PicturePath,
ThumbPath = _ThumbPath,
Description = MakeALT(FileName)
}
photoList.Add(p);
}
Upvotes: 2
Reputation: 680
In C# you can not create the Collections like that. To access or add an item to the Collection you should first create an instance of the collection you want to use.
In this case I suppose you want to use the List. So your code would be like following;
List<Photo> photoList = new List<Photo>();
for (int z = 0; z < xTotalNbrShown; z++)
{
Photo photo = new Photo();
photo.PicturePath = _PicturePath;
photo.PicturePath = _ThumbPath;
photo.PicturePath = MakeALT(FileName);
photosList.Add(photo);
}
Upvotes: 0