c# - Should a class that will run only once contain a static constructor? -


i beginning learn oop programming c#. concerning design, makes sense me use static constructor main class of program, considering class contains code run once (my whole program simple , consists of single .cs file).

for example, here's 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 file                  retcode = 0;   // ok             }             catch (exception ex) {                 console.writeline(ex.message);                  retcode = 999; // specific error             }              status = retcode;         }     } 

here follows same structure, using static constructor, think it's adequate. notice status access changed 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 file                  retcode = 0;             }             catch (exception ex) {                 console.writeline(ex.message);                  retcode = 999;             }              status = retcode;         }     } 


question: assumption correct, of using second code instead first one? or missing something? in other words: 1 preferable (considered better design)? , there fundamental on static constructors cause me trouble in case?

try avoid use of static constructors as possible. unlike instance constructors, cannot actively invoke static constructor - ran when type first being used (which may change due optimalisation or obfuscation).

also try avoid doing "work" in constructor. constructor meant construct instance, , nothing more.

so in both cases, move functionality method. method can have actual return value, rather setting property. since you're not maintaining state (program.status turned return value) can safely make method static.


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -