[Visual C#] The Hauntings of NullArgumentException

Started by
9 comments, last by Zahlman 14 years, 10 months ago
It could also be System.Console.WriteLine("| 1. {0}|", reader.ReadLine());. :) The idea is that the first argument to System.Console.WriteLine() is a "format" string, and anything else is a value to "substitute into" the format string. In your original code, you were supplying reader.ReadLine() and "|" as things to substitute in, but didn't specify anywhere to substitute them. The {#} parts of the format string indicate where to insert the other arguments - {0} for the first one after the format string, {1} for the next etc. This is described in detail in the MSDN documentation (see also).

But anyway, the point I wanted to make: repetition is the computer's job, not yours.

// We make a helper function first, which takes the file ID and substitutes it// in everywhere that it's needed - into the file name itself, and into the// output text.static void ShowName(int id) {  String fileName = String.format("name{0}.txt", id);  // We initialize the "name" to a default value, and overwrite that if the  // file is present. That way, there is only one statement in the code  // to do the actual printing.  String result = "Empty slot        ";  if (System.IO.File.Exists(fileName)) {    // Use a local variable for the file stream itself. Restrict scope as    // much as possible, in general.    FileStream file = System.IO.File.OpenRead(fileName);    System.IO.StreamReader reader = new System.IO.StreamReader(file);    result = reader.ReadLine();    reader.Close();  }  // Whether or not we read a slot name, we display whatever name we have  // at this point, labelled with the slot ID:  System.Console.WriteLine("| {0}. {1}|", id, result);        }// ----------------------- SHOW THE NAMESstatic void ShowNames() {  // Now all we have to do is loop over the slot IDs.  for (int i = 0; i < 3; ++i) { ShowName(i); }}


See? Much neater.

This topic is closed to new replies.

Advertisement