Search code examples
vb.netif-statementvisual-studio-2015booleanmy.settings

sampleVariable As Boolean = My.settings.sampleSettings (boolean dataType) doesn't work


I have a 2 scenarios that involves using My.Settings.sampleSettings with a dataType boolean and a sampleVariable as data type boolean.

Code: Since both sampleVariable and sampleSettings are boolean I declare them like that

Dim sampleVariable As Boolean = My.Settings.sampleSettings
Console.WriteLine("Result: " & sampleVariable)
If sampleVariable = False Then
    Console.WriteLine("1")
    sampleVariable = True
Else
    Console.WriteLine("2")
    sampleVariable = False
End If
My.Settings.Save()

Output: The output seems to not satisfy the condition 1, it always satisfies the condition 2 which is false

Result: False
1
Result: False
1
Result: False
1

Code: In this code I didn't put the sampleSettings to a boolean variable and it is working fine.

Console.WriteLine("Result: " & My.Settings.sampleSettings)
If My.Settings.sampleSettings = False Then
    Console.WriteLine("1")
    My.Settings.sampleSettings = True
Else
    Console.WriteLine("2")
    My.Settings.sampleSettings = False
End If
My.Settings.Save()

Output: Whenever I click the button it triggers a different condition, this is my goal.

Result: False
1
Result: True
2
Result: False
1

Question: How do I properly contain the My.Settings.sampleSettings to a boolean variable?


Solution

  • In the first block of code, you are not changing the value of the setting. You are only changing the value of the variable.

    sampleVariable = True
    

    This only changes the value of sampleVariable. It does not change the value of My.Settings.sampleSettings.

    In the second block of code, you are changing the value of My.Settings.sampleSettings, which is why the value is being saved.