I use protobuf-net to serialize/deserialize my data.
I have some rather simple classes, so that's no real problem.
As far as I know, protobuf-net uses IL generation to create serialization/deserialization code. While I have readonly fields in my model, I wonder how is it possible to write to such a field with IL? I can plainly see it works well, but I don't know why...
I've tried to spy it in the code, but it's a bit too complicated.
My attempts to generate such code myself always result in IL validator errors.
As I am quite interested in this discussion, I have tried Marc Gravell's example code and... it throws
VerificationException
on MS .NET 4.0.I've managed to make it work but I needed to use
DynamicMethod
constructor withowner
parameter set tofield.DeclaringType
even in case of publici
field.SkipVisibility
parameter seems to be redundant in this case.PS. I believe that this entry should be a comment, but due to the lack of rep I'm unable to comment other's answers.
Actually, I can't get it to fail - at least, when generating in memory.
Let's start simply, with a
public readonly
field (so we aren't breaking any accessebility rules); my first attempt is as below, and it works fine:The only time it gets interesting is if the field is
private
:The code above then gives the oh-so-vague:
But we get around that by pretending that the method is inside the field's declaring type:
Some other internal checks can be done by enabling
skipVisibility
:However, note that not all of this is possible if generating standalone assemblies. You are held to much higher standards when creating actual dlls. For this reason, the
precompiler
tool (to pre-generate assemblies) cannot handle quite the same range of scenarios that the in-memory meta-programming code can.