Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two values from GetValue reflection method

Tags:

c#

reflection

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;
}
like image 236
Malcolm Avatar asked Mar 17 '11 12:03

Malcolm


3 Answers

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)

like image 147
Migol Avatar answered Nov 10 '22 02:11

Migol


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:

  • https://learn.microsoft.com/en-us/dotnet/api/system.iequatable-1.equals?view=netcore-3.1
like image 4
Matías Fidemraizer Avatar answered Nov 10 '22 00:11

Matías Fidemraizer


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.

like image 3
LukeH Avatar answered Nov 10 '22 01:11

LukeH