views:

119

answers:

4

Can I rely on the fact that the underlying field to a property named Foo is called "k__BackingField" ?

A: 

Of course not. That would be a private implementation detail.

And why on Earth would you want to know?

John Saunders
Fixing a bug in Hessian's serialization. Auto properties are not serialized correctly, because they use the field's names.
ripper234
"Hessian's serialization"? Link, please? Never heard of it.
John Saunders
I assume http://www.hessiancsharp.org/
ShuggyCoUk
A: 

I don't think so. If you need the backing field, use a 'regular' property.

Tamás Szelei
+3  A: 

No, in short.

And for this very reason, auto-properties are pain when used with field-based serializers like BinaryFormatter (I'm sure I might have mentioned that here before ;-p).

See: Obfuscation, serialization and automatically implemented properties for some thoughts on this (and a solution).

Marc Gravell
+1  A: 

That the spec does not specify the backing field's name (with good reason - you shouldn't take a dependency on it).

You should investigate to see whether the Mono compiler does the same thing for example.

Sanity checking that the field had the CompilerGeneratedAttribute applied to it would be a good idea.

Note that explicit interface implementations would come out (currently) as:

<Full.Namespace.To.Interface.IBlah.Foo>k__BackingField

So code which is trying to serialize a specific aspect of a class in this fashion could be mislead.

If you wanted to be really belt and braces about your code you could use a library like mono's Cecil to inspect the get function of the property and determine the field used.

ShuggyCoUk
I just want it to work for me on Windows, nothing too fancy - but checking the attribute is an excellent idea, thanks.
ripper234