Cannot convert from out T in any type than string in c#

56 views Asked by At

This is my method for convert

public bool TryGetUserSetting<T>(string userSettingName, out T result)
        {
            try
            {
            var userSetting = Properties.Settings.Default[userSettingName];

            if (userSetting == null)
            {
                result = default!;

                return false;
            }

            result = (T)userSetting;

            return true;
        }
        catch (ConfigurationErrorsException)
        {
            result = default!;

            return false;
        }
    }

But only out result when is value string

if (!_userSettingsProviderService.TryGetUserSetting("SerialPortName", out string serialPortName) || !_userSettingsProviderService.TryGetUserSetting("SerialPortBaudRate", out int serialPortBaudRate)

            var serialName = serialPortName;
            var baudRate = serialPortBaudRate;

Return error for baudRate "Use of unassigned local variable 'serialPortBaudRate'.

1

There are 1 answers

1
Serg On BEST ANSWER

If a first call to TryGetUserSetting will return false, then condition will be immediately assumed as true (because of !TryGetUserSetting(...)). In this case the second call to the TryGetUserSetting will not be executed and serialPortBaudRate will remain unassigned. And you trying to use this unassigned variable inside if block. So, you can move declarations for out variables before if statements

string serialPortName = null;
int serialPortBaudRate = -1;
if (!_userSettingsProviderService.TryGetUserSetting("SerialPortName", out serialPortName) || !_userSettingsProviderService.TryGetUserSetting("SerialPortBaudRate", out serialPortBaudRate)

You can also replace conditional logical OR (||) with the ordinal logical OR (|) which will always calculate both arguments even the first one is true (see here for details), but this may be unobvious for someone who will read your code.