0
votes

I am utilizing protobuf-net for a project, and have a class that contains a double?[] member. As some of the values can be null, I need to run the following line of code:

RuntimeTypeModel.Default[typeof(MyType)][1].SupportNull = true;

I put this code in the static initializer for the class (e.g., in static MyType() { ... }), but when I run, I get an InvalidOperationException with the message "The type cannot be changed once a serializer has been generated". I suspect that this is due to the serializer being generated prior to the class being referenced for the first time. Does anyone know where to put this line of code so it always runs prior to serializer creation?

1

1 Answers

0
votes

Ah, I figured it out. The problem is that MyType inherits from BaseType. When I went to serialize/deserialize another type that inherits from BaseType, all of the serializers are built for all classes that inherit from BaseType. Then, at a later time the first reference to MyType was happening (which calls the static constructor), but the serializer for that type was already built.

To solve this I simply moved the aforementioned line of code into a BaseType static initializer. To clarify, the following illustrates my solution:

[ProtoContract]
[ProtoInclude(1, typeof(SubType1))]
[ProtoInclude(2, typeof(SubType2))]
public class BaseType {
    static BaseType() {
        // This runs prior to serializers being built,
        //     regardless of which subtype is used first
        RuntimeTypeModel.Default[typeof(SubType1)][1].SupportNull = true;
    }
    ...
}

[ProtoContract]
public class SubType1 : BaseType {
    [ProtoMember(1, OverwriteList = true)]
    public double?[] MyProp { get; set; }
    ...
}

[ProtoContract]
public class SubType2 : BaseType {
    ...
}