C # Serializing a collection of objects

I am working on an ASP.NET application that has a class that inherits from a custom object list.

public class UserRoleList : List<UserRoleBO> {
    public UserRoleList() { }
}

      

How do I make this class serializable in C #?

+2


source to share


3 answers


I believe you just need to make sure the UserRoleBO is serializable and the list will take care of itself. This assumes that the values ​​you want to serialize are public properties on UserRoleBO and UserList. For more information, see What is the point of the ISerializable interface?



+2


source


You need to do the following

  • Make sure UserRoleList is serializable
  • Make sure UserRoleBO is serializable
  • Make sure the type of all fields inside UserRoleBO is serializable (this is recursive)


The easiest way to do this is to add the [Serializable] attribute to the classes. This will work most of the time.

Another note, based on List<T>

, usually says a bad idea. The class is not intended to be inference, and any attempt to specialize its behavior may be thwarted in sceanarios where the derived class is used by reference List<T>

. Can you explain why you want to get this way? There is probably a more reliable solution.

+2


source


Same:

[Serializable]
public class UserRoleList : List<UserRoleBO> {
    public UserRoleList() { }
}

      

(Note that the "Serializble" tag must be on all classes to be serialized (so the parent.

And then use BinarySerialization for that.

+1


source







All Articles