0

I need some help understanding this, why it's happening and what I can do to fix it.

I got object A with some properties and a list of object B. Object B contains a decimal. Object A gets serialized into JSON as some point and saved for later use.

If i set object Bs decimal value to 100, serialize and then deserialize, the value returns as 100.0, causing the list comparison to return false.

Which means I can't compare an Object A that has been serialized and deserialized to an Object A that hasn't.

Copy/paste sample code below:

List<decimal> items = new List<decimal>();
items.Add(1.0M);

List<decimal> items2 = new List<decimal>();
items2.Add(1);

Console.WriteLine(items == items2); //false

decimal d = 1.0M;
decimal d2 = 1;

Console.WriteLine(d == d2); //true

Edit - added code example roughly what in my code:

public class ObjectA
{
    public string Name { get; set; }

    public List<ObjectB> Items { get; set; }
}

public class ObjectB
{
    public decimal Amount { get; set; }
}

static void Main(string[] args)
{
    ObjectA a1 = new ObjectA() { Name = "1", Items = new List<ObjectB>() { new ObjectB() { Amount = 1 } } };
    ObjectA a2 = new ObjectA() { Name = "1", Items = new List<ObjectB>() { new ObjectB() { Amount = 1.0M } } };

    Console.WriteLine(a1 == a2); //false
    Console.WriteLine(a1.Items.SequenceEqual(a2.Items)); //false
}
Gucchi
  • 33
  • 7
  • 5
    you are comparing here the reference of list not the values, to compare two list try this : ``items.SequenceEqual(items2)`` – Mohammed Sajid Mar 09 '20 at 20:51
  • 2
    `items == items2` is a reference comparison. Are they the same reference? No. So it will _never_ return true no matter what it contains. – Zer0 Mar 09 '20 at 20:59
  • It makes it harder to understand what you are after when you call it `objectA` and `ObjectB` in the text but `items` and `items2` in the code – Ňɏssa Pøngjǣrdenlarp Mar 09 '20 at 21:00
  • This has nothing to do with serialization, and everything to do with the fact that [`List` is a reference type and `decimal` is a value type](https://stackoverflow.com/questions/13049/). – Dour High Arch Mar 09 '20 at 21:06
  • Thanks for the helpful comments, but how do I make it so the comparison returns true? – Gucchi Mar 09 '20 at 21:13
  • 1
    like we said, after your edit, you still comparing references note values, you have two solutions: 1-use custom ``comparer`` for SequenceEqual or 2-change your code to : ``Console.WriteLine(a1.Items.Select(a => a.Amount).SequenceEqual(a2.Items.Select(a => a.Amount)))`` – Mohammed Sajid Mar 09 '20 at 21:24

0 Answers0