C#C
C#2y ago
tama

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:

C#
public class Car
{
    private string _manufacturer;
    private string _modelName;

    public string Manufacturer => _manufacturer;
    public string ModelName => _modelName;

    [Required]
    public string Owner { get; set; }

    public Car(string manufacturer, string modelName, string owner)
    {
        _manufacturer = manufacturer;
        _modelName = modelName
        Owner = owner;
    }
}

Is this sufficient?
Was this page helpful?