Will
Will

Reputation: 928

Protobuf-net serialization issue

This seems like a fairly simple use case, I don't understand how the exception in the following code snippet is being thrown.

static void Main(string[] args)
{
    using (var foobar = new MemoryStream())
    {
        ProtoBuf.Serializer.Serialize(foobar, new Foobar());
        if (foobar.Length == 0)
            throw new Exception("Didn't serialize");
    }
}

[ProtoContract]
public class Foobar
{
    [ProtoMember(1)]
    public int FoobarInt { get; set; }
}

Upvotes: 2

Views: 605

Answers (1)

JerKimball
JerKimball

Reputation: 16934

ProtoBuf is kinda weird...a zero-length serialized form is not "an error", per se...

Think of it this way:

if you wanted to *de*serialize a stream and get the empty object you tried to serialize, an empty stream would suffice (i.e., the "new" of the object would do the same thing) but if there's any data set on the object, now you need to actually save/load stuff

static void Main(string[] args)
{
    using (var foobar = new MemoryStream())
    {
        var foo = new Foobar() { FoobarInt = 1 };
        ProtoBuf.Serializer.Serialize(foobar, foo);
        if (foobar.Length == 0)
            throw new Exception("Didn't serialize");
    }
}

[ProtoContract]
public class Foobar
{
    [ProtoMember(1)]
    public int FoobarInt { get; set; }
}

Now produces a byte array of 0x08, 0x01

Upvotes: 1

Related Questions