Ashkan Mobayen Khiabani Ashkan Mobayen Khiabani - 6 months ago 29
C# Question

TryParse in if condition

I'm Getting a querystring data in ASP.NET C# and I need both its string value and int.Parse value of it (if it can be parsed). (in the example I'm skipping checking for null values as it has no effect on my question)

value = Request.QueryString["value"];
id = int.TryParse(Request.QueryString["value"], out id)

the code above does what I need but I just got curious if I could write it in one sentence so I tried this:

if (int.TryParse(Request.QueryString["value"], out id))) value=Request.QueryString["value"];

in this case I don't get the string value if it can't be parsed but I will get Its parsed value.

Any suggestions? I don't have a problem with my code I'm just asking out of curiosity that if it can be done in single line of code.

Answer Source

The almost-one-liner version would be

// id and value still need to be defined, of course!
int.TryParse(value = Request.QueryString["value"], out id)

Your code shouldn't work: if id is an int it won't be able to hold the bool coming out from TryParse.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download