need to init data stored in static class (use constructor? what if it fails?)

T

titan.nyquist

I need to initialize data to be stored in a static class (for all my
code to see), but I'm lost on how to do so.

If I use the class constructor, what if it fails? I am reading it
information from files that (could potentially) not exist. If it
throws an exception, it could be thrown wherever the first access to
the class is, which is undetermined. This seems like a bad idea.

Furthurmore, the data initialization code should be run at the
beginning of the program, to ensure if anything fails, it fails right
away.

How else could I do it? Any ideas?

I could create a method that the static class (the one that holds the
data) that I call when *I* choose to call it, right away at the
beginning of the program. That method could set a "dataInitialized"
boolean to be true, which ever access to the data could check (via
properties).

What do you think?

Titan
 
N

Nicholas Paldino [.NET/C# MVP]

Titan,

That's pretty much the best bet. If you are not concerned about your
code being run before you call this method, I would make the method empty
(do nothing) and then put the code in the static constructor for the class.

However, in order to control when the lifetime of things are created,
you have to make explicit calls (at least in this case).

Hope this helps.
 
T

titan.nyquist

Thanks, it does help.

1) I do want to control when the data init happens, and...
2) I do NOT want to have the constructor failing (let's say because it
couldn't read a file it needs to init that data) at undetermined spots
in my program.

I guess I already have the solution. Just wanted to check with the
experts.

Titan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top