2

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

ripper234
  • 222,824
  • 274
  • 634
  • 905
  • Re Hessian; why does it care about field names? property names would be more appropriate, no? If not, perhaps invent an attribute to name the member, i.e. [Hessian.Storage("foo")] public int Foo {get;private set;} – Marc Gravell Jul 23 '09 at 13:23
  • I'd rather just implement the hack of canonizing the name (k__backingField --> Foo) - it's easier on clients. – ripper234 Jul 23 '09 at 13:30
  • possible duplicate of [Problems with auto-properties](http://stackoverflow.com/questions/371398/problems-with-auto-properties) – nawfal Jun 03 '13 at 18:13

4 Answers4

5

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,026,079
  • 266
  • 2,566
  • 2,900
3

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
  • 36,004
  • 6
  • 77
  • 101
  • I just want it to work for me on Windows, nothing too fancy - but checking the attribute is an excellent idea, thanks. – ripper234 Jul 23 '09 at 14:23
  • I think its safe with explicit implementation as well, since the very name of the explicitly implemented property follows the pattern `Full.Namespace.To.Interface.IBlah.Foo`. – nawfal May 12 '13 at 13:59
0

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

And why on Earth would you want to know?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
0

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

Tamás Szelei
  • 23,169
  • 18
  • 105
  • 180