Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I call TryParse from within a Predicate

Tags:

c#

.net

How do I use the TryParse method within a Predicate? TryParse requires an out parameter. In the example below, I would like to call TryParse to determine if x can be converted to an integer. I really don't care for the out parameter--I just want to get this to compile.

        string[] nums = num.Split('.');
        PexAssume.TrueForAll(nums, x => int.TryParse(x, out (int)0));
like image 580
Pete Maroun Avatar asked Mar 02 '10 04:03

Pete Maroun


2 Answers

string[] nums = num.Split('.');
PexAssume.TrueForAll(nums, x => { int result; return int.TryParse(x, out result); });

The "expression" part of a lambda can be wrapped in braces, allowing a full function body with multiple statements. So long as the result of that body is the same as the return value of the implied function you are implementing, you can do whatever you need to do between those braces.

like image 195
jrista Avatar answered Oct 21 '22 23:10

jrista


If you don't care about the output, you can do it like this:

string[] nums = num.Split('.');
int unused;
PexAssume.TrueForAll(nums, x => int.TryParse(x, out unused)); 
like image 33
Gabe Avatar answered Oct 21 '22 22:10

Gabe