NameOf Expression

You now have access to the names of your code elements, such as variables and parameters. The .NET languages use the NameOf expression to enable this feature.

Prior to 2015, you often had to indicate the name of a program element by enclosing it in a string. However, if the name of that code element changed, you had an error lurking in your code (unless you managed to remember to change the string value). For example, consider the following code that throws an instance of ArgumentNullException. This class takes a string as the name of the argument. It then uses the string value to find your program element; it’s not strongly typed programming at all.

C#

public void SaveFeedback(string feedback)

{
    if (feedback == null)
    {
        //without nameOf
        throw new ArgumentNullException("feedback");
    }
}

VB

Public Sub SaveFeedback(ByVal feedback As String)
    If feedback Is Nothing Then
        'without nameOf
        Throw New ArgumentNullException("feedback")
    End If
End Sub

The NameOf expression eliminates this issue. You can use the expression along with your actual, scoped code element to pass the name of your code element as a string. However, NameOf uses the actual type to reference the name. Therefore, you get compile-time checking and rename support. The following shows an example of throwing the same exception as used earlier but using NameOf.

C#

throw new ArgumentNullException(nameof(feedback));

VB

Throw New ArgumentNullException(NameOf(feedback))

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset