OOP - Properties and Fields
Hello guys, sorry to disturb you all, consider the following code:
Noticed that we didn't defined the fields but only the properties which is used to get and set the variable.
I have some questions.
We didn't declare any fields or constructors, are the fields created automatically behind the scenes? For the constructor, we will be using the default constructor if nothing is provided?
13 Replies
If I wanted to use conditions in the properties, like Owner should only contain alphabets, how can I do so pls
here we would need to explicitly define the field?
For properties, backing fields will automatically be generated, yes
SharpLab
C#/VB/F# compiler playground.
yep I see, this is valid only if I don't modify them to add certain conditions ?
If you don't specify a custom constructor an implicit default constructor will be provided
Oh, yeah, if you want to modify the behaviour of the getter or setter you'll have to do some work yourself
There's an ongoing proposal / implementation to add a
field
keyword
But it's not quite there yet
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties#field-backed-propertiesthanks, will have a look !
Yw! Regarding your other question, if you want to add conditions to the properties, you could e.g. modify the setter to check the assigned value
yeah, I should follow the following syntax:
For the getter and setters ?
I think for the time being you'd be better off with using explicitly declared fields like showcased in https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/using-properties
Using Properties - C#
These examples illustrate using properties in C#. See how the get and set accessors implement read and write access and find out about uses for properties.
The
field
keyword requires you to turn on some language preview settingsyep I see, will just create a class, add some stuff and came back
Can someone explain why is the code above wrong please, my IDE is telling me get, set and value can't be resolved
The
()
parentheses are not valid syntax for properties
Just remove themahh yeah true
sorry