Michael,
Why not just take the code that is called in the constructor, refactor
it out to another method, and then have the LoadFromFile method call that
same code?
The only extra code you would have to add would be the code to
initialize the fields to the state they would be when you "new" up the
object (the constructor is called).
Other than that, it's a simple case of having to refactor the code.
Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
-
(E-Mail Removed)
"Michael A. Covington" <(E-Mail Removed)> wrote
in message news:(E-Mail Removed)...
> C# won't let me do something elegant.
>
> I'm creating a class and want to give it "write to file" and "read from
> file" methods. I'm actually using the XML serializer, but that's not the
> problem.
>
> The problem is that I cannot, after reading the data from a file, assign
> it to 'this'. So even though I have a fine method for
> foo.WriteToFile(filename), I can't implement foo.LoadFromFile(filename).
>
> One idea is that perhaps instead of LoadFromFile, I need a constructor
> that takes a filename as an argument. Is that the right approach?
>
> Of course, I can kluge my way around it by having LoadFromFile create
> *another* instance of the same class, then copy all the data, item by
> item, into 'this'. But that's inelegant, even though, seen from outside,
> it achieves exactly the desired effect. It's also error-prone because I
> might add something to the class and forget to copy it.
>
> Ideas?
>
>