Extract serialization of default values ​​in protobuf-net

In my project, I need not only time, but also information about the UTC offset. So I thought about using a class DateTimeOffset.

I did not do magic, just announced struct, containing shortfor offset and longfor ticks (same as in DateTimeOffset), and, of course, defining the attributes ProtoContractand ProtoMember.

But: even if this value is not initialized (both fields are zero), there are two more bytes per wire (I checked cross-checking with class)!

I tried to inherit DefaultValueAttributeand set the default value - but also to no avail.

The reason is that protobuf-net checks DefaultValueAttributeby name (in MetaType.ApplyDefaultBehaviour(bool isEnum, ProtoMemberAttribute normalizedAttribute)).

if ((attrib = GetAttribute(attribs, "System.ComponentModel.DefaultValueAttribute")) != null)
{
      object tmp;
      if(attrib.TryGet("Value", out tmp)) defaultValue = tmp;
}

But even if I change this, I get an exception in DefaultValueDecorator.Read(Compiler.CompilerContext ctx, Compiler.CodeLabel label), complaining:

 default:
      throw new NotSupportedException("Type cannot be represented as a default value: " 
                                     + expected.FullName);

Does anyone know the reason for this limitation?

Why not use default values ​​(T) for value types?

+4
source share

Source: https://habr.com/ru/post/1606280/


All Articles