Reflection GetValue null property
12,534
Instead of using LINQ and Where
method get the values to variables and put your condition inside loop:
foreach (var field in fields)
{
var val1 = objTarget.GetType().GetProperty(field).GetValue(objTarget, null);
var val2 = obj.GetType().GetProperty(field).GetValue(obj, null));
if(val1 == null and val2 != null || val1 != null && !val1.Equals(val2))
{
// your code
}
}
Author by
gog
Updated on July 22, 2022Comments
-
gog almost 2 years
This method compares two objects of the same class:
foreach (var field in fields.Where(field => !objTarget .GetType().GetProperty(field).GetValue(objTarget, null) .Equals(obj.GetType().GetProperty(field).GetValue(obj, null))))
If the both property have values it works normaly, but sometimes i have a null property in one of these 2 objects, how can i deal with it?
EDIT: If im comparing two objects, i.e:
var a = new Test(); var b = new Test(); a.Property1 = "1"; b.Property1 = null;
im getting the null reference exception:
An unhandled exception of type 'System.NullReferenceException' occurred in ConsoleApplication1.exe