1

I try to use XDocument (XML Linq) to save and load classes. For this I have two methods:

static MyClass FromXml(XElement data); //calls 0-parameter constructor inside
public XElement ToXml();

A constructor like this

public MyClass(XElement data)
{
    this = MyClass.FromXml(data);
}

does not work (says this is read only). Can this be done somehow (without creating copying each field manually from the returned value)?
Or is the very idea wrong?
Moving the code from FromXml to constructor should work, but then saving and loading would be in two places or constructors would not be all in one place...

Lukas
  • 2,232
  • 3
  • 21
  • 34
  • Maybe you could load the data inside the constructor into a temporary variable of type `MyClass` and then perform a value-copy like the one described here: http://stackoverflow.com/questions/3610891/c-copying-property-values-from-one-instance-to-another-different-classes – jCoder Jun 18 '11 at 20:55
  • 2
    Forget about that ctor and just use FromXml(). – H H Jun 18 '11 at 20:56

3 Answers3

5

I don't think you want a constructor; you want a static factory method that returns type MyClass. It looks like you already have that with method FromXml. You could always write a copy constructor that takes in another instance of MyClass if you really wanted.

TrueWill
  • 25,132
  • 10
  • 101
  • 150
5

I think you would need something like this:

public class MyClass
{
    public MyClass() {}
    public MyClass(XElement data)
    {
        loadXml(this, data);    
    }
    public static MyClass LoadXml(data)
    {
        var output = new MyClass();
        loadXml(output, data);
        return output;
    }
    private static void loadXml(MyClass classToInitialize, XElement data)
    {
        // your loading code goes here
    }
}
John Kalberer
  • 5,690
  • 1
  • 23
  • 27
1

You could create a non-public method static MyClass FromXml(XElement data, MyClass instance) which fills the passed-in instance using data. You can then call that from the constructor, passing this as an argument.

svick
  • 236,525
  • 50
  • 385
  • 514