I am writing one line of text in a file every time a button is pressed.
I have defined a static class like this:
public static class PalletRecord
{
public static string MachineName { get; set; }
public static DateTime TimeStamp { get; set; }
public static string BranchPlant { get; set; }
public static string Location { get; set; }
public static string Data { get; set; }
public static string ItemCode { get; set; }
public static string ItemDescription { get; set; }
public static decimal Quantity { get; set; }
}
Every time i need to write to a file i populate the static class properties and i use File.AppendAllLines to write to text file.
Should i have done it with a non-static class?
Yes ! Using statics to keep state like this is going to get you in trouble. This might especially be true if you might need multi threading now or in the future, since the static state is shared by all threads. Another problem could be an incomplete initialization bug, leaving you with ½ the state from a previous record and ½ the state from a new record.
A much better approach would be to make the properties non-static, and create one instance of the class with the correct properties for each record. You could make a constructor which sets the properties, so that you know you have a valid record whenever you have an instance (also consider making the property setters private).
This also better models the problem you are working with. You write multiple, different records in the file, this is best represented by instances of a class that represents a record. In my opinion, using an instance of your class for each record you need to write is the proper clean object oriented way to do this.