Take private string Property {get; set;}
versus private string field
.
Note that both are private (so they will not be exposed outside of this class) and that the property is not employing extra validation.
As regards semantics, do they have different meanings? In the sense that, are they interchangeable when used like this?
And when it comes to implications, such as (micro?) performance, does it matter if you create a field versus a property i.e. letting the compiler take care of the backing field for you.
The real difference is in their intended scope. Fields are meant to be private or protected in scope, meaning that access is restricted. Properties are meant to be public in scope, meaning that access is not restricted.
A field is a variable of any type that is declared directly in a class. A property is a member that provides a flexible mechanism to read, write or compute the value of a private field. A field can be used to explain the characteristics of an object or a class.
Properties are named members of classes, structures, and interfaces. Member variables or methods in a class or structures are called Fields. Properties are an extension of fields and are accessed using the same syntax.
Property works on compile and runtime. Method is a block of code that contain a series of statements. Method is explicitly called. Methods works on runtime.
When they're private the only difference I know is that the property is not suitable for out
and ref
parameters.
But mostly a private property does not deliver any advantages (over a field), so why bother?
There probably are (micro) performance costs. I would worry more about the extra clutter.
Performance implications:
There is a slight performance in using property (auto or with backing field) vs field since a property is a method and a CLR virtcall
needs to be called.
But as I said, there is not much point in using property and I believe a field is more readable as usually immediately visible by the naming convention (starting with underscore or camel casing).
You can't have a reference to a property, but you can get a reference to a member. Thus, if you use members, you might have trouble switching them to properties for whatever reason later, such as adding the notorious validation.
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