I am getting value1
and value2
which are both zero as not equal when they should be the same.
How else can I compare the values of these 2 objects?
private bool CheckProjectIsUnique(
TBR.Domain.Project project,
List<UniqueProjectType> types,
out UniqueProjectType uniqueCandidate)
{
uniqueCandidate = CreateUniqueProjectType(project);
if (types.Count == 0)
return true;
foreach (UniqueProjectType type in types)
{
bool exists = true;
foreach (PropertyInfo prop in type.GetType().GetProperties())
{
var value1 = prop.GetValue(type, null);
var value2 = prop.GetValue(uniqueCandidate, null);
if (value1 != value2)
{
exists = false;
break;
}
}
if (exists)
return true;
}
return false;
}
They are objects, so you should use value1.Equals(value2)
with checking if value1
is not null
EDIT: Better: use static Object.Equals(value1, value2)
(credits to @LukeH)
Equals is inherited from System.Object and it won't ensure that both objects would be correctly compared if you don't provide your own implementation of Equals.
Override System.Object.Equals and/or implement IEquatable<T>
in your domain objects or any object you want to eval its equality with another one.
Learn more reading this article:
Swap if (value1 != value2)
for if (!object.Equals(value1, value2))
and you should be good to go.
The !=
operator that you're currently using is non-virtual, and since the compile-time type of the GetValue
calls is object
you'll always be testing for reference (in)equality.
Using the static object.Equals(x,y)
method instead tests first for reference equality, and if the objects aren't the same reference will then defer to the virtual Equals
method.
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