Robb_2015
Robb_2015

Reputation: 397

pass a bool expression as a method parameter

i am a bit confused trying to implement a more elegant generic solution using lambda/LINQ Expression or Func<bool> to simply replace a bool return type.

say the expression is:

public bool someBoolRetMethod(someType parA, someOtherType parB) {
    if(parA==null)
        return new ExpM("relevant msg").Rtrn;
} 

so now if parA is null, ExpM() is a class that deals with errors

what i wanted to do is pass the condition as a parameter :

public class ExpBoolCond:ExpM {

    public bool Rtrn{get;set;}
    public ExpBoolCond(theBool, themsg) {
        variable to hold theBool;
        if(theBool) new specialMbxWindow(themsg)
        then set Rtrn..
    }
}

so in that way i could use:

 var condNullParA = new ExpBoolCond(parA==null, "passed ParA is Null,\r\nAborting method <sub>(methodName and line# is handled inside  ExpM base class)</sub> !")
if(condNullParA.Rtrn) ....

what is the correct way to implement it ?

Update :

 public class ExcBCondM:ExcpM
 {
     public bool Rtrn { get { return this._Rtrn(); } }
     Func<bool> _Rtrn { get; set; }
     public ExcBCondM(Func<bool> cond, string bsMsg)
        : base(bsMsg,false)
     {
        this._Rtrn = cond;
        //if (this._Rtrn) this.show();
     }
     public bool activateNon() { this.show(); return false; }
 }

usage:

public bool someBoolRetMethod(some_passed_Type parA)
{
    var someCondExpM =  new ExpBoolCond(() => parA==null, "relevant Message");
    if(someCondExpM.Rtrn) 
    return someCondExpM.activateNon(); //if() now Calls Func<bool> _Rtrn  when called rather where stated.
  return true;//if ok...
}

Upvotes: 2

Views: 6706

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727047

If you want to create Func<bool> as a lambda expression, the syntax is as follows:

var condNullParA = new ExpBoolCond(() => parA==null, "passed ParA is Null,\r\nAborting method <sub>(methodName and line# is handled inside  ExpM base class)</sub> !")
//                                 ^^^^^

The () => part tells C# compiler that the expression that follows should become a body of a lambda that takes no parameters, and returns whatever is the type of the expression to the right of the => sign, i.e. a bool.

Upvotes: 2

Related Questions