user3010406
user3010406

Reputation: 579

Object Property Comparison, best way to handle null checks?

I am looking through the FieldInfo of types, and collecting property information about the types. This code looks like this:

foreach (FieldInfo f in fi)
{
    Foo<T> v = new Foo<T>();
    v.Prop = f.Name;
    v.ValA = f.GetValue(val1);
    v.ValB = f.GetValue(val2);

    if (!v.ValA.Equals(v.ValB))
    {
        variances.Add(v);
    }
}

However, this code failed on the if condition, if v.ValA and v.ValB are null. I am looking for differences between objects with this, and if v.ValA is null and V.ValB are both null, it should fail the if condition. What would be the advised means on handling this?

Upvotes: 0

Views: 62

Answers (3)

Mike Perrenoud
Mike Perrenoud

Reputation: 67898

It should be as simple as this:

if (v.ValA == null || !v.ValA.Equals(v.ValB))
{
    variances.Add(v);
}

I say that because if v.ValA isn't null but v.ValB is it will evaluate to false anyway.

Upvotes: 1

MindingData
MindingData

Reputation: 12488

Just add another check to your if statement before your equals. e.g.

!(v.ValA == null && v.ValB == null)

Upvotes: 0

Noctis
Noctis

Reputation: 11763

You could do something like:

if ( !(v.ValA==null && v.valB==null) || !v.ValA.Equals(v.ValB))

If I read your question correctly

Upvotes: 0

Related Questions