Question

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

Was it helpful?

Solution

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).

OTHER TIPS

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.

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

And why on Earth would you want to know?

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top