views:

161

answers:

5

Is it possible to programmatically set that you want to exclude a property from serialization?

Example:

When de-serializing, I want to load up an ID field When serializing, I want to NOT output the ID field

(it's a silly example, but hopefully it's clear)

+2  A: 

If you are serializing to XML, you can use XMLIgnore

As in:

class SomeClass
{
  [XmlIgnore] int someID;
  public string someString;
}
Serapth
... and the NonSerialized attribute if you're using the BinaryFormatter or SoapFormatter.
Joe
+1  A: 

If you're using XML serialization, use the [XmlIgnore] attribute. Otherwise, how to ignore a particular property is defined by the serializer itself.

John Feminella
+2  A: 

If you want to include field during serialization but ignore it during deserialization then you can use OnDeserializedAttribute to run a method which will set default value for ID field.

Giorgi
+1  A: 

I believe there are three options here:

  1. Use XmlIgnore attribute. The downside is that you need to know in advance which properties you want the xmlserializer to ignore.

  2. Implement the IXxmlSerializable interface. This gives you complete control on the output of XML, but you need to implement the read/write methods yourself.

  3. Implement the ICustomTypeDescriptor interface. I believe this will make your solution to work no matter what type of serialization you choose, but it is probably the lengthiest solution of all.

Anax
A: 

It depends on serialization type. Here full example for doing this with BinaryFormatter:

You may use OnDeserializedAttribute:

[Serializable]
class SerializableEntity
{
  [OnDeserialized]
  private void OnDeserialized()
  {
    id = RetrieveId();
  }

  private int RetrievId() {}

  [NonSerialized]
  private int id;
}

And there is another way to do this using IDeserializationCallback:

[Serializable]
class SerializableEntity: IDeserializationCallback 
{
  void IDeserializationCallback.OnDeserialization(Object sender) 
  {
    id = RetrieveId();
  }

  private int RetrievId() {}

  [NonSerialized]
  private int id;
}

Also you may read great Jeffrey Richter's article about serialization: part 1 and part 2.

Sergey Teplyakov