Comparing the two values ​​of the GetValue method

I get value1 and value2 that are zero as not equal if they should be the same.

How else can I compare the values ​​of these two 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; } 
+6
reflection c #
source share
4 answers

These are objects, so you should use value1.Equals(value2) with validation if value1 not null

EDIT:. Better: use static Object.Equals(value1, value2) (credits for @LukeH)

+10
source share

Equals inherits from System.Object and does not guarantee that both objects will be correctly matched unless you provide your own implementation of Equals.

Override System.Object.Equals and / or implement IEquatable<T> in your domain objects or any object that you want to evaluate its equality with another.

Read this article for more details:

+4
source share

Translate if (value1 != value2) for if (!object.Equals(value1, value2)) and you should be good to go.

The != Operator that you are currently using is not virtual, and since GetValue type of compilation time for object , you will always test for reference (in) equality.

Using the static method object.Equals(x,y) instead checks first for referential equality, and if the objects do not match, the reference will be deferred until the virtual Equals method.

+2
source share

If the property type is a value type (for example, int), the value returned by GetValue will be placed in the object. Then == will compare the links of these values ​​in the box. If you want to have the correct comparison, you should use the Equals method:

 class Program { class Test { public int A { get; set; } } static void Main(string[] args) { var testA = new Test { A = 1 }; var testB = new Test { A = 1 }; var propertyInfo = typeof(Test).GetProperties().Where(p => p.Name == "A").Single(); var valueA = propertyInfo.GetValue(testA, null); var valueB = propertyInfo.GetValue(testB, null); var result = valueA == valueB; // False var resultEquals = valueA.Equals(valueB); // True } } 
+1
source share

All Articles