Given the struct S1:
unsafe readonly struct S1
{
public readonly int A1, A2;
public readonly int* B;
public S1(int a1, int a2, int* b)
{
A1 = a1;
A2 = a2;
B = b;
}
}
and an equality test:
int x = 10;
var a = new S1(1, 2, &x);
var b = new S1(1, 2, &x);
var areEqual = Equals(a, b); // true
areEqual evaluates to true, as expected.
Now lets slightly change our struct to S2 (replacing the pointer with a string):
unsafe readonly struct S2
{
public readonly int A1, A2;
public readonly string C;
public S2(int a1, int a2, string c)
{
A1 = a1;
A2 = a2;
C = c;
}
}
with an analog test:
var a = new S2(1, 2, "ha");
var b = new S2(1, 2, "ha");
var areEqual = Equals(a, b); // true
this evaluates to true as well.
Now the interesting part. If we combine both structs to S3:
unsafe readonly struct S3
{
public readonly int A1, A2;
public readonly int* B;
public readonly string C;
public S3(int a1, int a2, int* b, string c)
{
A1 = a1;
A2 = a2;
B = b;
C = c;
}
}
and test for equality:
int x = 10;
var a = new S3(1, 2, &x, "ha");
var b = new S3(1, 2, &x, "ha");
var areEqual = Equals(a, b); // false
The equality test fails, unexpectedly. Even worse,
Equals(a, a); // false
does also fail the test.
Why do the last two equality tests evaluate to false?
Edit
Bugreport for reference. Fixed in .net 6.0.