The NameOf
operator resolves namespaces, types, variables and member names at compile time and replaces them with the string equivalent.
One of the use cases:
Sub MySub(variable As String)
If variable Is Nothing Then Throw New ArgumentNullException("variable")
End Sub
The old syntax will expose the risk of renaming the variable and leaving the hard-coded string to the wrong value.
Sub MySub(variable As String)
If variable Is Nothing Then Throw New ArgumentNullException(NameOf(variable))
End Sub
With NameOf
, renaming the variable only will raise a compiler error. This will also allow the renaming tool to rename both with a single effort.
The NameOf
operator only uses the last component of the reference in the brackets. This is important when handling something like namespaces in the NameOf
operator.
Imports System
Module Module1
Sub WriteIO()
Console.WriteLine(NameOf(IO)) 'displays "IO"
Console.WriteLine(NameOf(System.IO)) 'displays "IO"
End Sub
End Module
The operator also uses the name of the reference that is typed in without resolving any name changing imports. For example:
Imports OldList = System.Collections.ArrayList
Module Module1
Sub WriteList()
Console.WriteLine(NameOf(OldList)) 'displays "OldList"
Console.WriteLine(NameOf(System.Collections.ArrayList)) 'displays "ArrayList"
End Sub
End Module