jeudi 14 janvier 2016

Are there cases where Fields are better than auto-properties

In terms of simple use, I perceive that Fields and Auto-Properties are functionally identical.

I'm aware of one case where they're substantially different: If you expose a property in a dll for a library and have other code using that dll, then (I believe?) you can change the property implementation, recompile the dll and replace the file, and the calling code doesn't need to be recompiled.

If what you exposed was a Field, then and change to "reimplement" that field as something more complex would require that the calling code be told about the change in some manner.

Another place where I repeatedly run into differences between Fields and Properties is in reflection-based libraries. E.g. CsvHelper or ServiceStack.Text, both of which will provide 'out-of-the-box' Serialisations, but which will only look at Properties, not Fields (as I just spent 2 hours realising :sad face: ). I think I had similar things with AutoMapper in the past too? It seems a relatively common thing.

It seems to me that I should therefore resolve to NEVER use a Field; that Properties are equal in the moajority of circumstances and VASTLY superior in others. The only downside is about 12 characters of extra "{get;set;}" in declarations.

Can anyone give counter-examples of either:

  • cases in general use where Fields are better than Properties?
  • libraries which rely on something being a Field NOT an Auto-property?




Aucun commentaire:

Enregistrer un commentaire