I am beginning to learn OOP programming with C#.
Concerning design, it makes sense to me to use a static
constructor for the main class of my program, considering this class contains code that will run only once (my whole program is very simple and consists of a single .cs file).
For example, here's a sample code using normal constructor:
class Program
{
const string file = @"C:\Program Files (x86)\myapp\log.txt";
int status;
static int Main(string[] args)
{
var myObj = new Program();
return myObj.status;
}
public Program()
{
int retCode;
try {
// lots of procedures using the file
retCode = 0; // ok
}
catch (Exception ex) {
Console.WriteLine(ex.Message);
retCode = 999; // specific error
}
status = retCode;
}
}
Here follows the same structure, but using static
constructor, as I think it's adequate. Notice status
access was changed as well.
class Program
{
const string file = @"C:\Program Files (x86)\myapp\log.txt";
static int status;
static int Main(string[] args)
{
return Program.status;
}
static Program()
{
int retCode;
try {
// lots of procedures using the file
retCode = 0;
}
catch (Exception ex) {
Console.WriteLine(ex.Message);
retCode = 999;
}
status = retCode;
}
}
Question: Is my assumption correct, of using the second code instead the first one? Or am I missing something?
In other words: Which one is preferable (considered better design)? And is there something fundamental on static constructors that will cause me trouble in this case?