Everyone has a different style.
I prefer to not perform any actions that might throw an exception in a ctor.
I use a Create/Load design (a two phase construction), where all the ctor
does is set state fields to known values, and a separate method performs the
operation. This makes cleanup logic much easier to implement and avoids side
effects. For example, if a static ctor throws an exception it renders that
type unusable for the life of the appdomain.
It also avoids ctors that take a l-o-n-g time to execute (which can create
its own set of problems). For example, what if the file is located on a
network where you are having intermittent connection problems? I prefer to
minimize my headaches by isolating operations. I pass arguments to ctors
when these values become part of the intial state of the object, not because
they force it to start an operation.
I recognize that many other people prefer doing it the other way...aint
choice grand.
"Gustaf Liljegren" <gu*****@algonet.se> wrote in message
news:uU**************@TK2MSFTNGP11.phx.gbl...
This may be a question of taste, but if there is a best practice, I want
to know. I have two choises:
SomeClass s = new SomeClass(file); // Load the file
or
SomeClass s = new SomeClass();
s.Load(file); // Load the file
The object 's' is constructed from contents of a file (or maybe a stream).
Is the contructor the natural place for reading file/stream contents into
an object, or is it better done separately, in a method?
I can think of one case when there's a need for a separate Load() method.
It's when you need to change properties of the object before feeding data
into it, like in:
XmlDocument x = new XmlDocument();
x.EntityResolver = null;
x.Load(file);
--
Gustaf