Reputation: 2941
NameValueCollection x = new NameValueCollection(Request.QueryString);
string x1 = x.ToString();
NameValueCollection y = HttpUtility.ParseQueryString(Request.QueryString.ToString());
string y1 = y.ToString();
when I execute above code, value of x1 and y1 become
x1="System.Collections.Specialized.NameValueCollection"
y1="abc=1&xyz=2" //url pass to controller is 'localhost/first/getresult/?abc=1&xyz=2'
I don't understand why the value of x1 and y1 is different
. I checked the documentation of ParseQueryString()
and it show that it return NameValueCollection
and I don't get any other information.
So, I don't understand why behavior is different of x
and y
.
Upvotes: 2
Views: 216
Reputation: 460238
In case of HttpUtility.ParseQueryString
an instance of the class HttpValueCollection
is returned(source) which inherits from NameValueCollection
. Obviously this classs overrides ToString
meaningfully as opposed to NameValueCollection
which inherits ToString
from object, hence just diplays the full-type name.
That's not mentioned in ParseQueryString
because HttpValueCollection
is internal
. They don't want you to use this type and you should not rely on this type being returned.
Here's the source of ToString
in HttpValueCollection
:
public override String ToString() {
return ToString(true);
}
internal virtual String ToString(bool urlencoded) {
return ToString(urlencoded, null);
}
internal virtual String ToString(bool urlencoded, IDictionary excludeKeys) {
int n = Count;
if (n == 0)
return String.Empty;
StringBuilder s = new StringBuilder();
String key, keyPrefix, item;
bool ignoreViewStateKeys = (excludeKeys != null && excludeKeys[Page.ViewStateFieldPrefixID] != null);
for (int i = 0; i < n; i++) {
key = GetKey(i);
// Review: improve this... Special case hack for __VIEWSTATE#
if (ignoreViewStateKeys && key != null && key.StartsWith(Page.ViewStateFieldPrefixID, StringComparison.Ordinal)) continue;
if (excludeKeys != null && key != null && excludeKeys[key] != null)
continue;
if (urlencoded)
key = UrlEncodeForToString(key);
keyPrefix = (key != null) ? (key + "=") : String.Empty;
string[] values = GetValues(i);
if (s.Length > 0)
s.Append('&');
if (values == null || values.Length == 0) {
s.Append(keyPrefix);
}
else if (values.Length == 1) {
s.Append(keyPrefix);
item = values[0];
if (urlencoded)
item = UrlEncodeForToString(item);
s.Append(item);
}
else {
for (int j = 0; j < values.Length; j++) {
if (j > 0)
s.Append('&');
s.Append(keyPrefix);
item = values[j];
if (urlencoded)
item = UrlEncodeForToString(item);
s.Append(item);
}
}
}
return s.ToString();
}
Upvotes: 4