2

I'm pretty new to C# and ASP.NET, so bear with me on this one. I'm setting up a page that receives query strings from the url. It then passes these strings to another method (in another class, actually), which goes on to do lots of things depending on the value of the query string.

The general structure looks something like this, where DoSomething() is actually part of another class that will be used by lots of different pages:

pretected void Page_Load (object sender, EventArgs e)
{
    DoSomething (Request.QueryString["name"]);
}

public void DoSomething (string UrlVariable)
{
    // if UrlVariable isn't set, initialize it to some value
    // do stuff with UrlVariable
}

Here's what I'm wondering:

  1. If the query string "name" isn't defined in the url, what does Request.QueryString return? an empty string? null?
  2. If it returns null, what happens if I try to pass null to a method that is expecting a string? Does the whole program fall apart, or can I check for null inside the DoSomething() method (after receiving the null string)?

The "name" is optional, so if the user doesn't set it, I'd like to detect that and initialize it to some default value. If possible, though, I'd like to put any validation inside DoSomething(), instead of doing the check on every page that requests the string.

Thanks in advance!

Michael Martin-Smucker
  • 11,927
  • 7
  • 31
  • 36
  • You could just try it :) If I'm not sure of how something will behave I'll knock up a quick test website to try it out. I've wrapped things like that inside properties in the past and that has worked out well for me. Depending on how your using it and how often you might want to store the value in a temp variable within your get accessor. – Antony Scott Nov 03 '10 at 17:22
  • Indeed, trying it wouldn't hurt -- I'm actually in the process right now. Since C# isn't exactly my specialty, though, I'm a little worried that I'll overlook something that could end up breaking the whole thing. Thus, I'm asking the experts. ;) – Michael Martin-Smucker Nov 03 '10 at 17:27

2 Answers2

4

If "name" isn't defined in the query string, it will indeed return null. If you attempt to pass null to a method (like string.Format for example), you will generally get a ArgumentNullException. A good way to handle this is to use a null-coalescing operator when passing a value into DoSomething for example:

DoSomething (Request.QueryString["name"] ?? "MyDefaultString");

Since DoSomething is yours though, you could choose to put this logic in there (depending on if it's reused or not) in order to keep your code DRY.

Steve Danner
  • 21,818
  • 7
  • 41
  • 51
1

1.) It should return null 2.) this is OK because strings are nullable; that being said you would want to check for it being null from the start of the function as you point out

Adam
  • 1,546
  • 2
  • 18
  • 23