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:
EDIT: Related but not identical: Public Fields versus Automatic Properties That seems to be a list of pros and cons, and I don't see ANY comments about advantages of fields, from a brief skim through. Feel free to post comments that are links to answers that I've missed in there.
From the question which you linked, the first answer https://stackoverflow.com/a/1180870/3419534 highlights one specific place where fields can be used and properties cannot, and that is as ref
parameters.
Consider:
int a;
int B { get; set; }
void F()
{
a = 0;
G(ref a); // a will be incremented
B = 0;
G(ref B); // Compiler error CS0206
}
void G(ref int p)
{
++p;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With