Search code examples
c#binaryformatterbinary-deserialization

BinaryFormatter.Deserialize HeaderHandler capture return value


I'm using the BinaryFormatter.Deserialize(Stream, HeaderHandler). I may have missed something obvious here but I can't find any examples online so I'm hoping someone can shed some light. I've passed in my delegate HeaderHandler that returns object but i don't know how to get hold of that object that it returns?


Solution

  • K; tracked through reflector. The only time the regular implementation uses this value is, when handling some data via remoting, if the value returned from the HeaderHandler is a MarshalByRefObject, in which case an identity is obtained and used for linking back. Specifically, the System.Runtime.Remoting.Messaging.MethodCall constructor.

    But all of that is an implementation detail! In most sane scenarios, the answer is: it isn't used.

    Indeed, the header-handling happens after the main deserialization, which rules out cheekily using the header-handler to set some values on the context object, which you then process.

    However, your header-handler can still update local variables:

    string someValue = null;
    object obj = serializer.Deserialize(source, headers => {
        // check the headers and assign someValue based on
        // what you find there; for brevity, make it up!
        someValue = "something from the headers";
        return null;
    });
    Console.WriteLine(someValue);
    

    Gotta love full lexical closures.

    Personally, though, I conclude: this isn't the way to do this. I would simply transfer a DTO with exactly the data you want to send.