Cleaner way to initialize application Settings to default values

823 views Asked by At

I have a class called LinearTransformation whose values I want to set during execution so that they are used next time, and then can be overwritten, etc.

Currently, I am verifying if there is a previous value and, if not, I set that value to a default one.

The problem is: my code has become repetitive, ugly, and most of it will only be useful the first time a new installation is run on a client machine.

Is there a more elegant way to achieve this?

    // This method is run when the app starts
    private void LoadCalibrações()
    {
        if (Properties.Settings.Default.CalibXEsq == null)
        {
            Properties.Settings.Default.CalibXEsq = new TransformaçãoLinear();
        }

        if (Properties.Settings.Default.CalibYEsq == null)
        {
            Properties.Settings.Default.CalibYEsq = new TransformaçãoLinear();
        }

        if (Properties.Settings.Default.CalibXDir == null)
        {
            Properties.Settings.Default.CalibXDir = new TransformaçãoLinear();
        }

        if (Properties.Settings.Default.CalibYDir == null)
        {
            Properties.Settings.Default.CalibYDir = new TransformaçãoLinear();
        }

        Properties.Settings.Default.Save();


        _calibrações = new[]
        {
            Properties.Settings.Default.CalibXEsq,
            Properties.Settings.Default.CalibYEsq,
            Properties.Settings.Default.CalibXDir,
            Properties.Settings.Default.CalibYDir
        };
    }
1

There are 1 answers

2
Matthew Whited On BEST ANSWER

If you just need to fill the array...

var settings = Properties.Settings.Default;
_calibrações = new[]
{
    settings.CalibXEsq ?? new TransformaçãoLinear(),
    settings.CalibYEsq ?? new TransformaçãoLinear(),
    settings.CalibXDir ?? new TransformaçãoLinear(),
    settings.CalibYDir ?? new TransformaçãoLinear(),
};

otherwise...

var settings = Properties.Settings.Default;
_calibrações = new[]
{
    settings.CalibXEsq ?? (settings.CalibXEsq = new TransformaçãoLinear()),
    settings.CalibYEsq ?? (settings.CalibYEsq = new TransformaçãoLinear()),
    settings.CalibXDir ?? (settings.CalibXDir = new TransformaçãoLinear()),
    settings.CalibYDir ?? (settings.CalibYDir = new TransformaçãoLinear()),
};