I am aware of the following quote:
The reason is that a lambda expression can either be converted to a delegate type or an expression tree - but it has to know which delegate type. Just knowing the signature isn't enough.
Trouble is I am still stuck on how to resolve my problem.
Can someone tell if the below is at all possible?
bool isStaff = () => { return selectedPerson.PersonType == "Staff"; };
Error:
Cannot convert lambda expression to type 'bool' because it is not a delegate type
I understand the error, but I really want to know how to fix this issue as I have rebounded off this error many times and simply not learnt to how properly use lamda expressions as far as value assignment is concerned.
Thanks for the quick replies fellas:
IMO, it would be awesome of the below was possible:
bool isStaff = (selectedPerson, bool) => { return selectedPerson.PersonType == "Staff"; };
Lol, I don't think that works but is beautiful in line code, to me that looks awesome and what I expect. The answers below seem to suggest otherwise lol!
The problem is that the lambda returns a bool
when it is evaluated, but it is not a bool
itself.
You can do the following:
Func<bool> func = () => { return selectedPerson.PersonType == "Staff"; };
bool isStaff = func();
This assigns the lambda to a variable, which can then be used to invoke the lambda, and return the desired bool
value.
bool isStaff = selectedPerson.PersonType == "Staff";
or
Func<Person, bool> isStaffDelegate = selectedPerson =>
selectedPerson.PersonType == "Staff";
bool isStaff = isStaffDelegate(selectedPerson);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With