Domanda

Given two object arrays I need to compare the differences between the two (when converted to a string). I've reduced the code to the following and the problem still exists:

public void Compare(object[] array1, object[] array2) {
    for (var i = 0; i < array1.Length; i++) {
        var value1 = GetStringValue(array1[i]);
        var value2 = GetStringValue(array2[i]);
    }
}

public string GetStringValue(object value) {
    return value != null && value.ToString() != string.Empty ?
        value.ToString() : "No Value";
}

The code executes fine no matter what object arrays I throw at it. However if one of the items in the array is a reference type then somehow the reference is updated. This causes issues later.

It appears that this happens when calling ToString() against the object reference. I have updated the GetStringValue method to the following (which makes sure the object is either a value type or string) and the problem goes away.

public string GetStringValue(object value) {
    return value != null && (value.GetType().IsValueType || value is string)
        && value.ToString() != string.Empty ? value.ToString() : "No Value";
}

However this is just a temporary hack as I'd like to be able to override the ToString() method on my reference types and compare them as well.

I'd appreciate it if someone could explain why this is happening and offer a potential solution. Thanks

Edit:

To help further explain my application. This piece of code is taken from an NHibernate event listener. I think the problem lies from NHibernate adding it's own wrapper around a class to deal with lazy loading. Here's the error it throws:

collection [*] was not processed by flush()

È stato utile?

Soluzione

It sounds like there may well be a side effect going on within the ToString() method for the reference type, which is generally bad practise as this is a method often used by the .NET framework.

For this to be the case the following would have to be true:

  • You are using a custom class that yourself or another 3rd Party built.
  • Some modification of the object occurs when calling ToString().

To verify this you could just create an instance of the reference type and call ToString() on it. See if the object has changed (GetHashCode() may be one way to determine this). Or you could inspect the code...

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top