Are there any cases when fields are better than auto-properties

From the point of view of simple use, I see that fields and auto-properties are functionally identical.

I am aware of one case when they differ significantly: if you set the property in the dll for the library and use different code using this DLL, then (I believe?) You can change the implementation of the property, recompile the dll and replace the file, and the call code does not need to recompile.

If what you set was a field, then change the "override" this field, because something more complex would require the calling code to be informed of the change in some way.

Another place where I repeatedly encounter differences between fields and properties is in reflection-based libraries. For example. CsvHelper or ServiceStack.Text, both of which will provide “ready-made” Serializations, but which will only consider properties and not fields (as I just spent 2 hours realizing: a sad face :). I think in the past I had similar things with AutoMapper? This seems relatively common.

It seems to me that I should allow NEVER to use the field; that Properties are equal in most circumstances and are VASTLY superior to others. The only drawback is about 12 characters of additional "{get; set;}" in the ads.

Someone can give counter examples:

  • in general, when are fields better than properties?
  • , -, -?

EDIT: , : , , , , . , , .

+4
4

, , fooobar.com/questions/12467/... , , , ref .

:

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;
}
+3

, , , - ref. Interlocked.CompareExchange().

, fooobar.com/questions/573905/... , Node.Next .

, . , , , , , , - .

+2

, auto, static readonly "" const, .

+1

" " , , . : " ", : . . -. *.

MSDN: *, .

, , : .

Of course, one thing that you cannot do with properties that you can use with fields is passed through them ref, but as soon as you immerse yourself in it, all the “best practices” can also be ignored.

*: taken with salt. There are reasons, but you should really know what you are doing, and why go against all the general tips.

+1
source

Source: https://habr.com/ru/post/1624292/


All Articles