Tuesday, November 30, 2010

TryParse

We want result to be set to the value of someObject.SomeProperty, and in any other case to default to 99.


int result = 0;
int max = int.TryParse(someObject.SomeProperty, out result) ? result : 99;

equivalent to

int result = 0;
int max = 99;

if(int.TryParse(someObject.SomeProperty, out result) == true)
{
max = result;
}
else // ok, maybe this 'else' is redundant
{
max = 99;
}

1 comment:

fc said...

How about this:

int result = 5;
_usersCount = int.TryParse(ConfigurationManager.AppSettings["UsersCount"], out result) ? result : result;