What is TryParse and Request.Form doing in this line of C# code?

565 Views Asked by At

What does this line of code do? I'm relatively new to C# and I've been trying to figure it out by reading about TryParse and Request.Form, however, I think a more comprehensive explanation would help me.

int.TryParse(Request.Form["yearhidden"], out year);

3

There are 3 best solutions below

0
On BEST ANSWER

TryParse is taking the value from Request.Form["yearhidden"]

Request.Form["yearhidden"] is a form field in your html called yearhidden.

TryParse then attempts to parse it into an integer value. It returns True if it was successful, False if not.

The value is stored in the variable year

0
On

Request.Form provides the form element posted to the HTTP request.

int.TryParse attempts to take this value and convert it to an integer.

In this case, you're taking the "yearhidden" form element's value, and attempting to convert it to an integer, which gets set in the year variable.

Note that you'd typically check the return value of int.TryParse, and handle the case where a non-numeric value was passed into the yearhidden variable.

0
On

int.TryParse returns a boolean that represents whether or not the method was able to parse the first parameter, Request.Form["yearhidden"], into an integer.

If it is able to successfully parse the value, the value of the second parameter, year, will be set to the value.

Request.Form contains all of the information within an html form element that was sent in a given request.

out is a keyword that forces arguments to be passed by reference.

http://msdn.microsoft.com/en-us/library/t3c3bfhx(v=vs.80).aspx