Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialization bugs in .NET?

I'm reading up on serialization, and have so far been messing with BinaryFormatter and SoapFormatter. So far, so good - and everything have both Serialized and Deserialized perfectly.

However, when I try the code below, I would expect my datafile to NOT contains the info for Name - and it does. Why would it contain that, when I specify SoapIgnore on the field?

I also tried with SoapAttribute("SomeAttribute") on the Age-field, and that didn't make any difference either. The framework version is set to 2.0, but the same thing happens in 3.5 and 4.0.

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

class Program
{
    static void Main(string[] args)
    {
        Person p = new Person();
        p.Age = 42;
        p.Name = "Mr Smith";

        SoapFormatter formatter = new SoapFormatter();
        FileStream fs = new FileStream(@"c:\test\data.txt", FileMode.Create);

        formatter.Serialize(fs, p);
    }
}

[Serializable]
class Person
{
    public int Age;
    [SoapIgnore]
    public string Name;
}
like image 435
Peter Olsen Avatar asked Dec 16 '22 22:12

Peter Olsen


1 Answers

Use [NonSerialized] instead of [SoapIgnore]

Furthermore, this is an older (and aging) API. Not directly wrong but be sure to read up on XmlSerialization and ProtoBuf as well.

And be careful not to mix the API's up. Serialization is part of SOAP communication but not the same. SoapAttribute is not involved in bare Serialization.

like image 83
Henk Holterman Avatar answered Dec 30 '22 07:12

Henk Holterman