I am wondering when it is appropriate to use global variables. I have an example as follows:
public partial class Form1 : Form
{
List<string> fileTypes = new List<string>();
private void btnManualBackup_Click(object sender, EventArgs e)
{
fileTypes.add("add stuff");
}
}
If I create the fileTypes list in the click function, it will create a new List every time the button is clicked, but I have also heard that it is bad practice to use global variables. Also, if a global variable in this instance is appropriate, is it best practice to store it at the top of the file or directly above the function that uses it?
In your example filetype isn´t global. It is private. If there is no keyword in front of a decleration it is normaly private. The use as shown in your code is fine. If you want to create the list with the first click you could change the code like this:
Global variables shouldn´t be used if possible.
public partial class Form1 : Form
{
private List<string> fileTypes; // private for clarification
private void btnManualBackup_Click(object sender, EventArgs e)
{
if(fileTypes == null) // If fileType is not created do it
fileTypes = new new List<string>();
fileTypes.add("add stuff");
}
}
There are other solutions depending on your C# version with the ?-opeator https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-coalescing-operator
About global variable, in c# they are normaly static and outside of a class. https://www.arclab.com/en/kb/csharp/global-variables-fields-functions-static-class.html