How to compute size of MessagePack .NET object?

342 Views Asked by At

If I have a class without any variable sized objects (e.g. strings, lists, etc.), is there some utility function in the MessagePack library to compute the size of the binary representation of the object?

Example class:

[MessagePackObject]
class Foo {
  [Key(0)]
  public int A { get; set; }
  [Key(1)]
  public float B { get; set; }
}

My current best bet is to simply serialize an object and measure it's length.

1

There are 1 best solutions below

1
On

Pass the final object to a helper method to get the bytes used, i.e.;

var obj = new Foo { A = 1, B = 2};
var bytes = Foo.ToMessagePack();
Debug.WriteLine($"size in bytes is {bytes.Length}");

And the extension method;

public static class Helpers
{
    public static byte[] ToMessagePack<T>(this T data) => MessagePackSerializer.Serialize(data);
}