damnDAN
damnDAN

Reputation: 25

How do I XML serialize a list from another class?

I have a list in a separate class. How do I transfer it to my separate Serializable class?

[Serializable]
public class ToSerialize
{
//code
}

Upvotes: 0

Views: 28

Answers (1)

Fildor
Fildor

Reputation: 16084

If I understand correctly, what you want to do is:

  1. Add a property to that class:
[Serializable]
public class ToSerialize
{
    public List<SomeType> MyList {get; set;}
}
  1. Assign the list to be serialized to an instance:
// somewhere in your code ...
var someList = new List<SomeType>(); // just to clarify what the List should look like
someList.Add(new SomeType()); 
// ...

var output = new ToSerialize();
output.MyList = someList; // assign the list to that property
  1. Serialize output

Note: For the List to be serializable, its contents (i.e. type "SomeType" in above example) need to be serializable.


While the above should take you one step further, you later may want to actually not assign the list itself, but a copy of it and its elements. This is commonly referred to as a "deep copy" or "deep clone", sometimes also "snapshot". Just in case you want to do some more research.

Upvotes: 1

Related Questions