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.