Home > Software design >  c# rewrite complex condition check logic using predicates
c# rewrite complex condition check logic using predicates

Time:07-15

What is the idea of c# Predicate ? Is it possible to rewrite complex condition check logic using predicates?

private bool HasChanged(object originalValue, object currentValue)
{
    if ((originalValue == null && currentValue != null) || 
        (originalValue != null && !originalValue.Equals(currentValue)))
    {
        return true;
    }
    
    return false;
}

CodePudding user response:

Predicate<T> is just a delegate that takes a T and returns bool. It's the equivalent of Func<T, bool> or a method with the signature bool Method<T>(T input).

It doesn't really help you here with your method.

You can, however, simplify your method to this:

private bool HasChanged(object originalValue, object currentValue) =>
    originalValue == null
    ? currentValue != null
    : !originalValue.Equals(currentValue);

CodePudding user response:

Try this:

bool HasChanged(object originalValue, object currentValue)
    => !(originalValue?.Equals(currentValue) ?? currentValue == null);

CodePudding user response:

You can use a predicate to check on object agains another object declaring the predicate as an object method. Something like

class MyClass
{
    public bool isValid(object obj)
    {
        if (obj is MyClass)
            return true;
        return false;
    }
}

public static class Program
{ 
    static int Main()
    {
        MyClass c1 = new ();

        Predicate<MyClass> predicate = c1.isValid;
        MyClass c2 = new ();
        if (predicate(c2))
        {
            Console.WriteLine("c1 is valid");
        }
        else 
        {
            Console.WriteLine("c1 is not valid");
        }

        return 0;
    }
}

CodePudding user response:

You could simplify this a little by flipping the logic and not attempting to cram it in to a single clause

private bool HasChanged(object originalValue, object currentValue)
{
    var bothNull = originalValue == null && currentValue == null;

    if (bothNull){
        return false;
    }

    // at least one of them is not null
    var areSame = originalValue?.Equals(currentValue) ?? false;

    return !areSame;
}
  • Related