Entity DB object with immutable variables
Hello there.
I am kind of new to C# and I am doing a project about some database management system. I have created an object for the database and my first migration went well. Now, part of the challenge with this project is that some class variables for the database object needs to be readonly after being set in the initializer. I am a little unsure if this is something you can achieve with some keywords or if I need to create my own logic for ensuring the fields are never changed. As an example:
I have a class Car with three variables: Manufacturer, Model and Owner. Now, Manufacturer and Owner will always stay the same for the object in the database but Owner can of course change. To achieve this, I have so far written:
Is this sufficient?
8 Replies
You can just use init properties
public string Manufacturer { get; init; }
Let me just try, maybe you are right. 🙂
Alright, it seems to work, thanks a lot. 🙂
Just one last thing: Is it possible to showcase that it is not possible to write to the variable after calling the initializer? I'm thinking an xunit test?
Yeah, a unit test sounds good
That said... I'd quwstion unit testing the framework
Like, you don't unit test whether
Math.Max()
actually returns the maximum value, of if Console.WriteLine()
actually works
Or if a private method really is privateYeah, I am aware it is not the best practice, however, part of the criteria for the project is that the variable cannot be changed after initialization, so it could be nice to be able to point to a unittest and say: "Look, it's not being changed!"
If that's the case, then sure, write a test
Assuming you can
Since trying to assign to an init property is a compile-time error, not a runtime exception IIRC
I just wonder how... I tried doing something like this but it would not build because it's an obvious error:
Yep
Best idea I have, is to write a separate little project, and show the build error
Yeah, it's probably not worth the time at that point, since there are still a bunch of features I need to add. I appreciate the help though. 🙂