Inheritance Serializers

Learn how to serialize classes and any their children classes.

Another frequently asked question is how to handle serialization for classes which are inherited by multiple other classes. These are often used to allow RPCs to use the base class as a parameter, while permitting other inheriting types to be used as arguments. This approach is similar to Interface serializers.

Class example

Here is an example of a class you want to serialize, and two other types which inherit it.

public class Item : ItemBase
{
    public string ItemName;
}

public class Weapon : Item
{
    public int Damage;
}

public class Currency : Item
{
    public byte StackSize;
}

/* This is a wrapper to prevent endless loops in
* your serializer. Why this is used is explained
* further down. */
public abstract class ItemBase {}

Using an RPC which can take all of the types above might look something like this.

Creating the writer

Since you are accepting ItemBase through your RPC you must handle the different possibilities of what is being sent. Below is a serializer which does just that.

Finally, disclosing why we made the ItemBase class. The sole purpose of ItemBase is to prevent an endless loop in the reader. Imagine if we were able to return only Item, and we were also using that as our base. Your reader might look like this...

The line return reader.Read<Item>(); is the problem. By calling read on the same type as the serializer you would in result call the ReadItem method again, and then the line return reader.Read<Item>(); and then ReadItem again, and then, well you get the idea.

Having a base class, in our case ItemBase, which cannot be returned ensures no endless loop.

Last updated