In the last tutorial, I showed you how to do a quick web client to find out if a particular site contains the keywords that you are interested in. Today, we’ll make a small addition. We are going to add command line parameters, so we can look for the U.S. job situation on a whim.

Command line parameters allow us to add settings to a program when it is being launched, so that our program’s users can choose where and what to look for without having to recompile the program.

If we look at the main method we did earlier, we can see that it accepts the following parameter:

string[] args

This means that any parameters from the command line are contained in this array of strings.

Let’s say that we are going to accept two parameters: the first one for the url to be checked, and the second one for the keywords to find. If only one or no parameters are passed, we will default to our settings that were used in the previous example. The following code is used to read the url parameter:

var url = args.Length > 0 && Uri.IsWellFormedUriString(args[0],
UriKind.Absolute) ? args[0] : "http://www.gametrailers.com";

Here we are creating a new variable called url and setting it to a value. Now comes the interesting part. We are using a ternary operator to set this value. A ternary operation has the following format.

(condition) ? (value when true) : (value when false)

So it is really a shorthand to check for a particular condition and set a value accordingly. It is mostly used when the condition has two possible outcomes. In the conditional statement we check if there are any command line parameters (args.Length > 0) and (&&) the 1st parameter (args[0]) is a well formed url. The ternary operator then takes care that if both of these conditions are true, we use the passed url, otherwise we use the default gametrailers url.

Next we do the same with the keywords parameter:

var keywords = args.Length > 1 ? args[1] : "final fantasy";

This time we only check if there is a second parameter (args.Length > 1) and use it (args[1]) if true or the default keywords. Now let’s end by trying some searches.

The full version of the code is also available on github here.