A method for value equality regardless of reference equality #77333
-
Object would benefit from containing a method to check for value equality regardless of whether or not a type is a value type or a reference type. I've written an idea as to how this could be implemented. The reason I think this could be useful, is that there are cases where creating a class over a struct is necessary (or in cases where you didn't write the classes being checked for equality) and don't need to know whether or not they are the same instance, and only whether the states are the same. Take a Bitmap class, ValueEquals would return true even if the classes were initialized separately, if the data it contains is the same (ie. all pixels match up.) public static bool ValueEquals ( this object obj, object other )
{
if ( obj.GetType () != other.GetType () )
{
return false;
}
else if ( obj.GetType ().IsValueType )
{
return obj.Equals ( other );
}
else if ( ReferenceEquals ( obj, other ) )
{
return true;
}
foreach ( FieldInfo info in obj.GetType ().GetFields ( BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance ) )
{
if ( info.FieldType.IsValueType )
{
if ( !info.GetValue ( obj ).Equals ( info.GetValue ( other ) ) )
{
return false;
}
}
else
{
if ( !info.GetValue ( obj ).ValueEquals ( info.GetValue ( other ) ) )
{
return false;
}
}
}
return true;
} |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 12 replies
-
This appears to be an api request. moving to dotnet/runtime. That said, it looks like you have your solution, so i'm not sure what need there would be for an actual runtime method for this :) |
Beta Was this translation helpful? Give feedback.
-
I think "value equality" would have to be very thoroughly defined. WHat is value-equality in the presence of cycles? What is it for arrays? If you have things like dictionaries/sets, what is it in terms of ordering of elements? etc. etc. etc. I have a feeling the only suitable approach here is for certain types to opt into stating they are value equatable and defining themselves what that means. |
Beta Was this translation helpful? Give feedback.
This appears to be an api request. moving to dotnet/runtime. That said, it looks like you have your solution, so i'm not sure what need there would be for an actual runtime method for this :)