0

In order to set option strict ON on my code I get error on code which actually work OK.

    Public Function ModifyRegistryKey(ByVal rClass As String, ByVal rKey As String, ByVal rValName As String, ByVal rValue As String) As Integer

    'Grant Read, Write and Create permissions for the key
    Dim f As New RegistryPermission(RegistryPermissionAccess.Read Or _
                                    RegistryPermissionAccess.Write Or _
                                    RegistryPermissionAccess.Create, rKey)

    Dim regKey As Object
    Try
        'Check if it exists. If it doesn't it will throw an error
        regKey = My.Computer.Registry.CurrentUser.OpenSubKey(rKey, True).GetValue(rValName)
    Catch ex As Exception
        regKey = Nothing
    End Try

    If regKey Is Nothing Then
        'It doesn't exist here. Create the key and set the key name and value.
        regKey = My.Computer.Registry.CurrentUser.CreateSubKey(rKey)

        regKey.SetValue(rValName, rValue) 'LATE BINDING HERE

    Else
        'Registry key exists
        If Not regKey Is rValue Then
            My.Computer.Registry.SetValue(rClass & "\" & rKey, rValName, rValue)
        End If
    End If
End Function

Why I get error message: "Option Strict On disallows late binding." and how to get rid of late binding here?

Wine Too
  • 4,515
  • 22
  • 83
  • 137

1 Answers1

2

You've declared regKey as Object and then you're trying to call Microsoft.Win32.RegistryKey methods on it but I guess the compiler doesn't know it's going to be of type Microsoft.Win32.RegistryKey.

As an aside, your exception handling usage isn't best practice, I assume the exception is occurring because OpenSubKey() is returning Nothing but this isn't exceptional so you should just code for it.

I've created an example which I think is better, and it does compile - although I haven't tested it because I don't want to nail my registry, and I'm not sure why you have two ways of setting the values, so I've just commented out your second way, might be something I'm missing when editing registrys...

Public Sub ModifyRegistryKey(ByVal rKey As String, ByVal rValName As String, ByVal rValue As String)
    Dim registryKey As Microsoft.Win32.RegistryKey

    registryKey = My.Computer.Registry.CurrentUser.OpenSubKey(rKey, True)

    If registryKey Is Nothing Then
        registryKey = My.Computer.Registry.CurrentUser.CreateSubKey(rKey)
    End If

    If registryKey.GetValue(rValName) Is Nothing _
    OrElse CStr(registryKey.GetValue(rValName)) <> rValue Then
        registryKey.SetValue(rValName, rValue)
        'My.Computer.Registry.SetValue(rClass & "\" & rKey, rValName, rValue)
    End If
End Sub
ForkandBeard
  • 874
  • 10
  • 28