Properties vs Fields in C#
Hello guys, can someone explain what is the difference between Properties and Fields in C# please. At first I thought that properties and fields were the same thing because they are accessed the same way, like writing
person.name
something like that. But this isn't the case. How do properties work? I noticed they work as method but they don't have any parentheses. They should be named the same way as the fields?
12 Replies
$propvsfield
Why use properties over a public field?
- Properties can individually specify access modifiers for get and set
- With Visual Studio, you can type prop, press tab and it will auto complete for you
- XAML requires properties for bindings
- Field exposure is really only done in readonly structs
- Using properties allows for future changes to the getter or setter without breaking your API/external programs (binary compatibility)
Example of an auto property:
Example of a property with backing field:
They don't have to be named the same as the field. They don't even need to be tied to a field, necessarily
For example, you could have
or
yep I see, but one thing... the properties acts as method, why they don't have parentheses ?
I mean how the compiler know this isn't a field
because the compiler understands the syntax used to define properties, namely the { } with get and/or set inside
ahhh I see
Noted, thanks guys ! 👍
it's just syntactic sugar, after compiling it will be methods set_Age and get_Age, but marked to be special
yeah, like behind the scenes, the compiler would still process it like set_Age(int age)... ?
yup, and some code that says the property Age has those as set/get method
$getsetdevolve
can be shortened to
can be shortened to
can be shortened to
can be shortened to
The compiler would produce something like the first example from any autoproperty