I’m trying to convert some VB.net code into C# and having issues trying to convert this one line.
VB.NET
Dim myreg As Microsoft.Win32.Registry
I know it’s a static so I can’t create an instance but when I tried a VB.NET converter to C# the website gives me this:
Microsoft.Win32.Registry myreg = null;
And gives me an error message: ‘Microsoft.Win32.Registry’ is a ‘type’ but is used like a ‘variable’
In the last part of the Function in VB.NET, myreg is used:
Finally
myreg = Nothing
End Try
Here’s the whole function:
Imports System.Data.OleDb
Imports System.Data
Imports Microsoft.Win32.RegistryKey
Imports MyLogger 'custom reference, not worried about this.
Private Function getRegistryString(ByVal sVal As String, Optional ByVal sKey As String = "") As String
Dim myreg As Microsoft.Win32.Registry
Dim s As String
Try
s = myreg.LocalMachine.OpenSubKey(sKey).GetValue(sVal)
Catch ex As Exception
l.EventLog(ex.Message, EventLogEntryType.Error)
Throw ex
Finally
myreg = Nothing
End Try
Return s
s = Nothing
End Function
In VB.NET, there is no way to define a shared (static) class. In C#, however, you can specify that a class is static. When a class is static, it forces all its members to be static as well. The compiler will give you an error if you try to declare a variable of a static type.
In VB, however, since there is no such thing as a shared class, it always allows you to declare a variable of any type, even though it’s entirely pointless because the instance will have no members.
Instead of declaring a variable as type
Registry, you need to change the code to simply use theRegistryclass name, itself. Setting the variable toNothingis meaningless because the variable never stores a reference to an object. It’s alwaysNothing.Your function should read like this: