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'.
If a first call to
TryGetUserSetting
will returnfalse
, then condition will be immediately assumed astrue
(because of!TryGetUserSetting(...)
). In this case the second call to theTryGetUserSetting
will not be executed andserialPortBaudRate
will remain unassigned. And you trying to use this unassigned variable insideif
block. So, you can move declarations forout
variables beforeif
statementsYou can also replace
conditional logical OR (||)
with the ordinallogical OR (|)
which will always calculate both arguments even the first one istrue
(see here for details), but this may be unobvious for someone who will read your code.