How come we can explicitly set a property that doesn't have a setter method?

https://www.codecademy.com/courses/learn-c-sharp/lessons/csharp-interfaces/exercises/finish-truck-class

Hi,

In a part of the code in the solution from the link above, it sets the value of a property without a setter which raises no issues. However, upon incrementing the property, it throws an error. Why is this?

Thanks in advance for any help.

I can’t see the code that is used but at a guess this is what is happening:
The value for the property is being set in a constructor. The constructor can set the value of a property even if it doesn’t have a setter. I won’t go into how auto properties work behind the scenes but I’d say simply take it as a rule that the constructor can do it.

This behaviour makes sense when you think about it. Many times you may want to create an object that can’t be changed (or at least certain values) but you don’t know them when writing the code, or they may change. The constructor allows you to set them once and then they can’t be changed but can still be read and used. You may not be able to see the value in doing that right now (or you might) but it is a very common use case.

1 Like

That’s what I thought. Thanks for the help!