Serializing List<T>?

J

jp2msft

Can I serialize a List<T>?

I created a Serializable class with integers, strings, and a DateTime.

To make it powerful, I used this class to create a List.

Visual Studio 2005 Pro will not serialize the List. Specifically, the
Exception Message says:

Message = "Type 'Report.PaySetting+Bonus+Shift' in Assembly 'Report,
Version=1.0.0.4, Culture=neutral, PublicKeyToken=59a931376efc8b7c' is not
marked as serializable."

Since I am only trying to serialize a List, there must be errors with it.
Right?

How would I Serialize this class?

[Serializable]
public class Bonus {
public class Shift {
public int JointMinimum;
public int DaysWorkedMinimum;
public int PassRateMinimum;
public Shift(int MinimumJoints, int MinimumWorkdays, int
MinimumPassRate) {
JointMinimum = ((0 < MinimumJoints) && (MinimumJoints < 10000)) ?
MinimumJoints : 1000;
DaysWorkedMinimum = ((0 < MinimumWorkdays) && (MinimumWorkdays <
64)) ? MinimumWorkdays : 20;
PassRateMinimum = ((0 < MinimumPassRate) && (MinimumPassRate <
100)) ? MinimumPassRate : 50;
}
}
public DateTime CreationDate;
public Shift FirstShift;
public Shift SecondShift;
public Shift ThirdShift;
public Bonus(DateTime historicDate, Shift firstShift, Shift
secondShift, Shift thirdShift) {
CreationDate = (historicDate == new DateTime(1900, 1, 1)) ?
DateTime.Now : historicDate;
FirstShift = (firstShift != null) ? firstShift : new Shift(0, 0, 0);
SecondShift = (secondShift != null) ? secondShift : new Shift(0, 0,
0);
ThirdShift = (thirdShift != null) ? thirdShift : new Shift(0, 0, 0);
}
}
List<Bonus> m_history;
 
A

Alberto Poblacion

jp2msft said:
Can I serialize a List<T>?

Yes, on the condition that T is Serializable.
[...]
How would I Serialize this class?

[Serializable]
public class Bonus {
public class Shift {
[...]
}
public Shift FirstShift;
[...]

You are missing a [Serializable] attribute on class Shift.
It's not enough to mark a class (such as Bonus) as Serializable.
Everything contained inside that class needs to be itself Serializable.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top