❔ properties/constructor question
Why do we need another variable (model = modelName) ? Why cant we just set it like this
Sorry for such a basic question 🙏
14 Replies
So, first things first, there are no properties in your code, just public fields
And if you want something like that, you can use records
Why do we need to assign the values explicitly? Well, what if you want to modify them somehow, or do some conditional logic?
oh i see, because then you would permanently alter the value instead of just for that object, right?
Not sure what you mean
Here's what I mean
You might want to modify the values somewhat before setting the props
Is this considered setting?
Well, yeah
I also see the set; too, but just curious why we need it if we're setting the value in the constructor?
Sorry ive been trying to wrap my head around this, tyvm
It sets the
Model
property
{ get; set; }
is what makes a property
A default getter and a default setter
They can have more code in them, of course
But the idea is to put a layer on top of the class's data. The data remains private (properties generate private fields on compile time) but the accessors are public
Encapsulation and all thatright right
If you want the property to be settable just from the constructor, you can have just
{ get; }
, no problemOh, wait so
for this example, set; in this case is just an extra layer of protection, because we're setting the value in the constructor
?
set;
allows the value to be set even outside of the constructor, from the outside of the class
can be shortened to
can be shortened to
can be shortened to
can be shortened to
thank you! I also didnt know what the => meant i kept seeing so thats hepful as well. tysm!
It's expression-bodied method
The thing to the right of
=>
has to be an expression or a one-liner statementWas this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.