Home > Software engineering >  Using getter in C#
Using getter in C#

Time:09-29

I've made a class called Device which has the following properties:

public int Id { get; }
public string DeviceName { get; set; }
public string MACAddress { get; set; }
public string UUID { get; set; }
public string SerialNumber { get; set; }
public string Location { get; set; }
public string PinCode { get; }

I use these properties to get information from my database.

I then want to update the device in my database using the following:

private void _updateDeviceInDataBase()
{
    DataAccess database = new DataAccess();
    Device device = new Device()
    {
        DeviceName = textBox_PcNumber.Text,
        SerialNumber = DeviceProperties.GetSerialNumber(),
        UUID = DeviceProperties.GetUUID(),
        MACAddress = DeviceProperties.GetMACAddress(),
        Location = comboBox_Location.Text,
    };

    database.UpdateDevice(device);
}

My problem is, that my Id and my PinCode is null, because I obviously don't set them in my device variable.

My question then is - how do I make use of the properties Id and PinCode in my device, without having to change them to set?

CodePudding user response:

You can init get-only properties in the constructor..

public class Device
{
    public int Id { get; }
    public string DeviceName { get; set; }
    public string MACAddress { get; set; }
    public string UUID { get; set; }
    public string SerialNumber { get; set; }
    public string Location { get; set; }
    public string PinCode { get; }

    public Device(int id, string pinCode)
    {
        Id = id;
        PinCode = pinCode;
    }
    // other code ...
    // public Device(){} // uncomment this if you want to call new Device();
}

If initiating Id, PinCode properties is not required, you can uncomment // public Device(){} line.

Thanks to @Franck comment, you can set Id, PinCode properties via setter injection

public class Device
{
    public int Id { get; private set; }
    public string DeviceName { get; set; }
    public string MACAddress { get; set; }
    public string UUID { get; set; }
    public string SerialNumber { get; set; }
    public string Location { get; set; }
    public string PinCode { get; private set;}
    
    public void SetId(int id) => Id = id;
    public void SetPinCode(string pinCode) => PinCode = pinCode;

    // other code ...
}
  •  Tags:  
  • c#
  • Related