Class inherited from List<T> not serializing?

Hi all and happy new year!

I just ran across an unexpected behaviour with regards to serialization and was hoping you could help me. Take the following code:

[Serializable]
public class ListInt : List<int> {}

[SerializeField] List<int> genericList;
[SerializeField] ListInt inheritedList;

//in a custom editor, when a button is clicked:
if(genericList == null){genericList = new List<int>();}
if(inheritedList == null){inheritedList = new ListInt();}
genericList.Add(0);
inheritedList.Add(0);
Debug.Log("Generic: " + genericList.Count + " - Inherited: " + inheritedList.Count);

Surprisingly, while genericList gets serialized just fine, inheritedList does not. Is this a known limitation, or am I just doing something wrong?

The reason I’m messing with all this is because I was hoping to create a quick and easy serializable Dictionary by just inherting from Dictionary<string, int> for example.

Thanks in advance,
Patrick

Nope, List serialization is a special case thing in the unity serializer.

Dictionary isn’t serializable, and inheriting from it doesn’t really change anything about that fact either.

You can write a serializable dictionary, and you can inherit from Dictionary to do so (or write a custom class that implements IDictionary and wraps around a Dictionary). You’ll have to also implement ISerialializationCallbackReceiver though and turn the keys and values into data that can be serialized on Deserialize and Serialize calls.

1 Like

I actually tried doing this before and ended up wondering just like you. What @lordofduct said is exactly the case. List handling is hardcoded. You can read the serialization logic code by inspecting Data/Managed/SerializationLogic.dll - you need to implement your own serialization system to handle those edge-cases. ISerializationCallbackReceiver is key.

An example implementation of such system is VFW. Dictionaries, along with many other types (even nested generic types) are all supported.