I have a an Class that has a Bitmap property. I have implemented an Equals override for the object and I'm having an issue with Bitmap comparison. Here is what I have:
[Serializable]
public class Contact
{
public string Name { get; set; }
public Bitmap Photo { get; set; }
public override bool Equals(object obj)
{
if (obj == null) { return false; }
if (obj.GetType() != typeof(Contact)) { return false; }
Contact compareContact = obj as Contact;
if (compareContact.FirstName != this.FirstName) { return false; }
if (compareContact.Photo != null && this.Photo != null)
{
if (!compareContact.Photo.IsEqual(this.Photo)) { return false; }
}
else
{
if (!(compareContact.Photo == null && this.Photo == null)) { return false; }
}
return true;
}
}
public static class BitmapExtensions
{
public static bool IsEqual(this Bitmap image1, Bitmap image2)
{
if (image1 == null || image2 == null)
{
return false;
}
byte[] image1Bytes = image1.ToByteArray();
byte[] image2Bytes = image2.ToByteArray();
bool sequenceEqual = image1Bytes.SequenceEqual(image2Bytes);
return sequenceEqual;
}
public static byte[] ToByteArray(this Bitmap image)
{
using (MemoryStream ms = new MemoryStream())
{
image.Save(ms, ImageFormat.Bmp);
return ms.ToArray();
}
}
}
And My Test:
[TestClass()]
public class vCardTest
{
private Contact TestContact()
{
Contact contact = new Contact();
contact.Name = "Joe";
contact.Photo = new System.Drawing.Bitmap(1, 1);
}
[TestMethod]
public void EqualsTest()
{
Contact matchedContact = Common.Copy<Contact >(TestContact);
Assert.AreEqual<vCard>(vcf, matchedVCard);
}
And my Copy Method:
public static T Copy<T>(T objectToCopy) where T : class
{
byte[] serializedObject = objectToCopy.Serialize();
T copy = serializedObject.Deserialize(typeof(T)) as T;
return copy;
}
My Equals function returns false. When I look at the byte arrays for the original bitmap and the copy, I notice two bytes out of 58 within the arrays are off by one. The two byte arrays have the same length.
I'm trying to figure out if the serializing and deserializing the bitmap to make a copy is causing the issue, or something else.
Update
It doesn't appear that the Common.Copy method is causing the issue, this code with byte arrays works successfully:
[TestMethod()]
public void ByteArrayCommonCopyTest()
{
byte[] byteArray1 = new byte[] { 0, 1, 1, 0, 123, 45, 56, 0 };
byte[] byteArray2 = Common.Copy<byte[]>(byteArray1);
bool expected = true;
bool actual;
actual = byteArray1.SequenceEqual(byteArray2);
Assert.AreEqual(expected, actual);
}
Interestingly, if I update Photo to a new Bitmap with same size, it works:
[TestMethod]
public void EqualsTest()
{
Contact matchedContact = Common.Copy<Contact>(TestContact);
matchedContact.Photo = new System.Drawing.Bitmap(1, 1)
Assert.AreEqual<vCard>(vcf, matchedVCard);
}