MGOwen
MGOwen

Reputation: 7269

ASP.NET: Using Request["param"] versus using Request.QueryString["param"] or Request.Form["param"]

When accessing a form or query string value from code-behind in ASP.NET, what are the pros and cons of using, say:

// short way
string p = Request["param"];

instead of:

// long way
string p = Request.QueryString["param"]; // if it's in the query string or
string p = Request.Form["param"];        // for posted form values

I've thought about this many times, and come up with:

Short way:

Long way:

.

So what other advantages/disadvantages are there to each approach?

Upvotes: 3

Views: 6733

Answers (2)

Andrew
Andrew

Reputation: 14447

The long way is better because:

  • It makes it easier (when reading the code later) to find where the value is coming from (improving readability)

  • It's marginally faster (though this usually isn't significant, and only applies to first access)

In ASP.NET (as well as the equivalent concept in PHP), I always use what you are calling the "long form." I do so out of the principle that I want to know exactly from where my input values are coming, so that I am ensuring that they get to my application the way I expect. So, it's for input validation and security that I prefer the longer way. Plus, as you suggest, I think the maintainability is worth a few extra keystrokes.

Upvotes: 4

Kris Ivanov
Kris Ivanov

Reputation: 10598

the param collection includes all (4) collections:

  1. Query-string parameters
  2. Form fields
  3. Cookies
  4. Server variables

you can debate that searching in the combined collection is slower than looking into a specific one, but it is negligible to make a difference

Upvotes: 9

Related Questions