2

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; }
}

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

This is correct. I over simplified my actual problem for the sake of an simple example. I actually use data contracts. I had a class with 2 properties references other classes. I forgot to include the Order property of the data member attributes in the referenced classes. So that's why it wasn't serializing anything.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.