We're using a System.Windows.Forms.ImageList to store a bunch of Images that
I've loaded, and rendering each image in the ImageList during a draw loop.
The process was running unusually slow and was causing memory spikes. After
several hours we discovered that the ImageList.Images indexer is actually
returning a copy of the added Images instead of simply returning a reference.
Needless to say, we were a bit surprised and disturbed to discover this.
1) Can anyone answer why the ImageList collection returns a copy instead of
a reference?
2) Is there a way to get the reference instead of a copy?
If you run the example code below, the output to the console window will be
"Different Image".
// Example Code
System.Windows.Forms.ImageList imageList =
new System.Windows.Forms.ImageList();
System.Drawing.Image image =
System.Drawing.Image.FromFile(@"C:\image.png");
imageList.Images.Add(image);
// Get the same Image twice!
System.Drawing.Image imageFromList1 = imageList.Images[0];
System.Drawing.Image imageFromList2 = imageList.Images[0];
if (object.ReferenceEquals(imageFromList1, imageFromList2))
{
Console.WriteLine("Same Image");
}
else
{
Console.WriteLine("Different Image");
}
Console.ReadLine();