write twice, method once

My brother Genji always says, “Measure twice, cut once”. After hearing him say this enough, I tried to apply it to my life and hobbies, and realized that in programming it’s the opposite. You don’t want to reuse code if you don’t have to. Let me show the full title now. Never write twice, method once. I realize that looks weird now, but the point still stands. If you have to use a piece of code more than once, you should probably make a method/function for it.
Let’s look at an example

Say you wanted to print out the contents of an array at multiple points within your program. Instead of having multiple for loops, you could just create one function, like this.

public void printArray(string[] myArray)
foreach (string s in myArray)



Writing text to files in visual C# (.NET)

Ok, ok. Writing text to files with C# is pretty easy. You just throw in that good old System.IO.File.WriteAllLines([path], [string array]);

But, what if you don’t want to explicitly ask the user (or yourself) for the path every time?
That’s where the SaveFileDialog class comes in handy.
Instead of having to ask the user for the path each time, you can simply do this instead:
1. Instantiate the class: SaveFileDialog SFD = new SaveFileDialog();
2. Set a filter if you so desire: SFD.Filter = "Text File|*.txt|All Files|*.*"; (This causes that handy-dandy drop-down of different file types to appear like when you save files with notepad and other editors.)
3. Set the title of the save dialog: SFD.Title = "Save the File";
4. Show the save dialog: SFD.ShowDialog();
5. Check to make sure the file name is not empty: if (SFD.FileName != "") { System.IO.File.WriteAllLines(SFD.FileName, [string array]); }
Notice how you never have to prompt the user for the file path, you can easily retrieve it by referencing SFD.FileName, as the file name is actually the path to the file, including it’s name.

For opening files, you can use the OpenFileDialog which works almost exactly like SaveFileDialog.