Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a condition into Func<bool> of a Tuple<string, string, Func<bool>>

I am trying to create a list of tuples with properties and conditions for their validation. So I had this idea in mind:

List<Tuple<string, string, Func<bool>>> properties = new List<Tuple<string, 
                                                                    string,
                                                                    Func<bool>>> 
{
    Tuple.Create(FirstName, "User first name is required", ???),
};
...

How can I pass expression of type (FirstName == null) as Func ?

like image 457
eYe Avatar asked Jun 23 '15 14:06

eYe


2 Answers

Like this (using a lambda expression):

var properties = new List<Tuple<string, string, Func<bool>>> 
{
    Tuple.Create<string, string, Func<bool>>(
                 FirstName, 
                 "User first name is required",
                 () => FirstName == null),
};
like image 112
Yuval Itzchakov Avatar answered Sep 28 '22 01:09

Yuval Itzchakov


Something like this:

List<Tuple<string, string, Func<bool>>> properties = new List<Tuple<string, string, Func<bool>>> 
{
    Tuple.Create(FirstName, "User first name is required", new Func<bool>(() => FirstName == null)),
};

Note that there are some limitatons to type inference for lambda expressions... for this reason the new Func<bool> way of building a delegate is used.

Alternatives:

Tuple.Create(FirstName, "User first name is required", (Func<bool>)(() => FirstName == null)),
Tuple.Create<string, string, Func<bool>>(FirstName, "User first name is required", () => FirstName == null),
new Tuple<string, string, Func<bool>>(FirstName, "User first name is required", () => FirstName == null),

In the end you have to repeate the Func<bool> somewhere.

like image 28
xanatos Avatar answered Sep 28 '22 02:09

xanatos