Hanshan
Hanshan

Reputation: 3764

C# Reflection Property.GetValue() Problem

I am having a problem with the following code:

int errorCount = 0;
foreach (var cinf in client.GetType().GetProperties())
{
    var vinf = viewModel.GetType().GetProperty(cinf.Name);
    if (vinf != null)
    {
        if (cinf.GetValue(client, null) != vinf.GetValue(viewModel, null))
        {
            errorCount++;
        }
    }
}

It's for an automated test to see whether mapping a model object from a DTO has worked. If I use the more cumbersome approch of writing this for each property:

Assert.AreEqual(viewModel.ClientCompanyID, client.ClientCompanyID);

This works fine.

The problem is: the reflection code evaluates "if val1 != val2" statement incorrectly (or so it seems). If I step through this code, the evaluation basically says "1 does not equal 1", and incorrectly adds an error. Furthermore, if I test this with this code, I get the same seemingly false result:

var clientEx = client.GetType().GetProperty("ClientCompanyID");
var viewModelEx = viewModel.GetType().GetProperty("ClientCompanyID");
var clientVal = clientEx.GetValue(client, null);
var viewModelVal = viewModelEx.GetValue(viewModel, null);
bool test = (clientVal == viewModelVal);

The bool returns false even when, stepping through the code, clientVal = 1 and viewModelVal = 1. See attached picture.

alt text

Any help with this would be greatly appreciated!

Thanks guys.

Tim.

EDIT: Could have given you all the answer. Glad it was simple in the end. Thanks alot for your help. Cheers.

Upvotes: 2

Views: 5465

Answers (3)

Aliostad
Aliostad

Reputation: 81700

This is only natural. If you compare to objects together using ==, it will compare their reference which is different.

Use objectA.Equals(objectB).

Upvotes: 1

cdhowie
cdhowie

Reputation: 169363

You need to compare with object.Equals() instead of using reference equality. Boxed value types will not compare as equal without using object.Equals(). Try this:

if (!object.Equals(cinf.GetValue(client, null), vinf.GetValue(viewModel, null)))

For example, take this simple case:

csharp> object a = 1;
csharp> object b = 1;
csharp> a == b;
false
csharp> object.Equals(a, b);
true

Upvotes: 3

SLaks
SLaks

Reputation: 888117

You're comparing to different boxed integers by reference.

Change it to

if (!Equals(cinf.GetValue(client, null), vinf.GetValue(viewModel, null))

This calls the static Object.Equals method, which will call the virtual Object.Equals method (after checking for null) to compare objects by value.

You'll see the same issue for strings.

Upvotes: 1

Related Questions