6

I have a somewhat complicated Class that may or may not contain a list of items of the same type

Class Items
{
   List<Items> SubItems ...

}

The class itself is serializeable, however its going to be a giant waste of space to serialize the objects in the list since they are serialized and added to the database prior to being included in the list.

Is there a way that I can specify that the list should be represented as a list of integers when its serialized ?

Note: These integers will represent primary keys of the rows where the serialized object is located.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
TacticalMin
  • 791
  • 2
  • 7
  • 18

3 Answers3

1

Is there a way that I can specify that the list should be represented as a list of integers when its serialized?

Yep. There are two main options:

1) Implement the ISerializable-Interface, where you can control how the object will be serialized / deserialized.

OR

2) Declare your List as [NonSerialized] and also manage a private Member List, which contains your primary keys. You will have to implement the logic for loading / storing the Integer-List by your own, though.

If your class to serialize is quite big, I would recommend you the second approach, because in the other case you have to manually serialize / deserialize each property.

Fabian Bigler
  • 10,403
  • 6
  • 47
  • 70
1

To specify how an object is serialised, you need to implement ISerializable and provide an implementation for GetObjectData

public virtual void GetObjectData(SerializationInfo info, StreamingContext context) 
{

}

There is a simple example on this MSDN page:

http://msdn.microsoft.com/en-us/library/ms973893.aspx

dougajmcdonald
  • 19,231
  • 12
  • 56
  • 89
1

If you only want to save space, you can use DataContractSerializer to achieve that. It has preserveObjectReference option. Which doesn't duplicate same object instead only store referenceId.
Detail here

dbc
  • 104,963
  • 20
  • 228
  • 340
nhrobin
  • 873
  • 2
  • 7
  • 14