views:

63

answers:

1

Hi I need to serialize several fields of my class

class Foo
{
 Guid value1;
 decimal value2;
 SomeCustomEnum value3;
}

Can I serialize all fields one by one:

            MemoryStream ms = new MemoryStream();
            SoapFormatter sf = new SoapFormatter();
            sf.Serialize(ms,value1;
            sf.Serialize(ms, value2);
            sf.Serialize(ms, value3);
            string data = Convert.ToBase64String(ms.ToArray());
            ms.Close();
+2  A: 

Mark the fields you do not want to serialize with [NonSerialized]. That way you can skip the third party fields.

    [Serializable]
    class Foo
    {
        Guid value1;
        decimal value2;
        SomeCustomEnum value3;

        [NonSerialized]
        int Skip = 12;
    }

[Edit] New example after comment about inheritance. You can control your serialization manually:

class Foo
{
 public Guid value1;
 public decimal value2;
 public SomeCustomEnum value3;
}

[Serializable]
class Bar : Foo, ISerializable
{
 private int a;

 public Bar()
 {
 }

 #region Implementation of ISerializable
 public void GetObjectData(SerializationInfo info, StreamingContext context)
 {
  info.AddValue("a", a);
  info.AddValue("value1", value1);
  info.AddValue("value2", value2);
 }

 protected Bar(SerializationInfo info,StreamingContext context)
 {
  a = info.GetInt32("a");
  value1 = (Guid)info.GetValue("value1", typeof(Guid));
  value2 = info.GetDecimal("value2");
 }
 #endregion
}
Mikael Svenson
Good idea. But what if my class is derived from third-party class that is not market as serialized?
Captain Comic
In my added example you could probably loop over all properties with reflection if you don't want to hand-craft it.
Mikael Svenson