Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize 'System.Numerics.Complex' using an XmlSerializer?

This is the XML output I get when a Complex[] object is serialized:

<MyClass>               
    <Complex />
    <Complex />
    <Complex />
    <Complex />
</MyClass>

The Complex struct is marked as serializable, and being a struct, it has an implicit parameterless constructor. So why isn't each Complex object serializing its real and imaginary parts ? Does it have to do with the fact that the 'Real' and 'Imaginary' properties of the struct have getters but not setters ?

Thanks.

like image 677
alhazen Avatar asked Jul 28 '26 17:07

alhazen


1 Answers

It depends on the implementation of the serializer you are using to serialize the object.
If you try this, you will get what you are expecting:

using System.IO;
using System.Numerics;
using System.Runtime.Serialization.Formatters.Soap;

public class Test {
    public static void Main() {
        var c = new Complex(1, 2);
        Stream stream = File.Open("data.xml", FileMode.Create);
        SoapFormatter formatter = new SoapFormatter();
        formatter.Serialize(stream, c);
        stream.Close();
    }
}

Instead, if you use classes in the System.Xml.Serialization namespace, you will get something similar to what you posted:

using System;
using System.IO;
using System.Numerics;
using System.Xml.Serialization;

public class Test {
    public static void Main() {
        var c = new Complex(1, 2);
        XmlSerializer s = new XmlSerializer(typeof(Complex));
        StringWriter sw = new StringWriter();
        s.Serialize(sw, c);
        Console.WriteLine(sw.ToString());
    }
}

I think that this is due to the fact that the XmlSerializer will not serialize private members (as are m_real and m_imaginary in the Complex struct).

like image 57
Paolo Tedesco Avatar answered Jul 30 '26 05:07

Paolo Tedesco



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!