Note: For Assert
, using Xunit
Anonymous objects use value equality:
Assert.Equal(
new { foo = "bar" },
new { foo = "bar" }
);
Anonymous arrays with anonymous objects use value equality:
Assert.Equal(
new [] { new { foo = "bar" } },
new [] { new { foo = "bar" } }
);
Anonymous objects with nested arrays seem to use reference equality (this fails):
Assert.Equal(
new { baz = new [] { new { foo = "bar" } },
new { baz = new [] { new { foo = "bar" } }
);
But this works (presumably because there's now reference equality):
var baz = new [] { new { foo = "bar" } };
Assert.Equal(
new { baz },
new { baz }
);
And this works (so it appears I can recursively nest anonymous objects with value equality preserved):
Assert.Equal(
new { baz = new { qux = new { foo = "bar" } } },
new { baz = new { qux = new { foo = "bar" } } }
);
I'm not sure how equality is being conducted here, but I'd like to be able to nest objects and arrays and have infinite-depth value equality. How might I go about doing that?
Update
Looks like Fluent Assertions solved my problem (this test passes):
(new { baz = new[] { new { foo = "bar" } } })
.Should()
.BeEquivalentTo(new { baz = new [] { new { foo = "bar" } } });
In other words, we can also say that an operator is a symbol that tells the compiler to perform specific mathematical, conditional, or logical functions. It is a symbol that operates on a value or a variable. For example, + and - are the operators to perform addition and subtraction in any C program.
%d is a format specifier, used in C Language. Now a format specifier is indicated by a % (percentage symbol) before the letter describing it. In simple words, a format specifier tells us the type of data to store and print. Now, %d represents the signed decimal integer.
-= Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand. C -= A is equivalent to C = C - A.
For anonymous types, their Equal
and GetHashCode
implementation is the result of recursively running Equal
or GetHashCode
on their properties. So if you have two anonymous classes with similar value-type properties with the same values, then they compare as equal.
However, if any property is a reference-type, and it does not point to the same object, then they won't be equal.
Here is the snippet from Microsoft docs [1]:
Because the Equals and GetHashCode methods on anonymous types are defined in terms of the Equals and GetHashCode methods of the properties, two instances of the same anonymous type are equal only if all their properties are equal.
Now, as why arrays are equal, I would bet it is the Assert.Equal implementation that checks if the objects are enumerable, then it check their items equality.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With