3

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:

  • Shorter (more readable, easier for newbies to remember, etc)

Long way:

  • No problems if there are a form value and query string value with same name (though that's not usually an issue)
  • Someone reading the code later knows whether to look in URLs or form elements to find the source of the data (probably the most important point)

.

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

MGOwen
  • 6,562
  • 13
  • 58
  • 67

2 Answers2

9

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

Kris Ivanov
  • 10,476
  • 1
  • 24
  • 35
  • 3
    +1 The only performance difference is that the first time `Params` is accessed, it needs to be constructed from the other collections. `NameValueCollection` uses a `Hashset` to store the values, so access is quick regardless of size. – Vadim Feb 09 '11 at 03:25
  • 1
    I sometimes deliberately set up just `Request["param"]`. I do this so that I can use both POST and GET in other pages that point to this one but are for the same purpose (like a returnUrl to be used with OAuth for example). I certainly don't think that this should just be done by default due to laziness, though, for sure. – VoidKing Aug 23 '13 at 15:53
4

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.

MGOwen
  • 6,562
  • 13
  • 58
  • 67
Andrew
  • 14,325
  • 4
  • 43
  • 64