Reputation: 4033
Why converting / parsing string to int return 0 / zero?
On debug, using the breakpoint, I could see "3" posted to browse action as a string value but when i convert to int as above, the value is converted to 0 value of int type.
//
// GET: /Event/Browse
public ActionResult Browse(string category)
{
int id = Convert.ToInt32(category);
// Retrieve Category and its Associated Events from database
var categoryModel = storeDB.Categories.Include("Events").Single(g => g.CategoryId == id);
return View(categoryModel);
}
Take a look at the image below for better understanding:
Another image - categoryModel getting null on LINQ query.
Upvotes: 2
Views: 4472
Reputation: 10381
From MSDN on Int32.TryParse here
When this method returns, contains the 32-bit signed integer value equivalent to the number contained in s, if the conversion succeeded, or zero if the conversion failed. The conversion fails if the s parameter is nullptr, is not of the correct format, or represents a number less than MinValue or greater than MaxValue. This parameter is passed uninitialized.
Upvotes: 5
Reputation: 27441
If your Parse() call fails and your exception is uncaught or you don't test the return value of TryParse(), then surely the int variable would remain as it was - initialized by default to zero.
For example, this would keep your int a zero:
int i;
Int32.Parse("FAIL!");
// i is still a zero.
So instead try this:
int i;
bool parseSuccessful = Int32.TryParse("123", out i);
// parseSuccessful should be true, and i should be 123.
Or to see it fail gracefully:
int i;
bool parseSuccessful = Int32.TryParse("FAIL!", out i);
// parseSuccessful should be false, and i should be 0.
Upvotes: 4