C# - Calling ToString() on a Reference Type

Posted by nfplee on Stack Overflow See other posts from Stack Overflow or by nfplee
Published on 2012-11-07T16:59:02Z Indexed on 2012/11/07 16:59 UTC
Read the original article Hit count: 218

Filed under:
|
|

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() : "";
}

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() : "";
}

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

© Stack Overflow or respective owner

Related posts about c#

Related posts about object