This site runs best with JavaScript enabled.

Why does the Nameof operator in VB.NET return the member name with the wrong case?

Spencer Schneidenbach

April 14, 2016

nameof is one of my favorite operators in C# 6 – it’s a little thing that makes life a little easier.  I use it a lot in Entity Framework 6 with the ForeignKey attribute and when throwing ArgumentExceptions so that I don’t have to have magic strings everywhere.

I discovered some interesting behavior regarding Nameof in VB.NET that I thought took VB.NET’s case insensitivity to the next level:

Class Program
    Sub Main()
        Dim firstNameOf = Nameof(YourClass.FirstName)
        'Output: FirstName
        Dim secondNameOf = Nameof(YourClass.fIRsTnAMe)
        'Output: fIRsTnAMe
    End Sub
End Class

Public Class YourClass
    Public Property FirstName As String
End Class

See the difference in outputs?  FirstName versus fIRsTnAMe?  I mean, c’mon, really?  The Nameof operator returns exactly what you type inside of it and not the actual properly cased member name??

This actually caused me a fair bit of grief the other night – I was using Nameof with the ForeignKey attribute in EF and kept getting these odd exceptions where it said it couldn’t find the member called Firstname – and all because I mistyped the casing for the property (FirstName.)

I’ve always had a soft spot for VB.NET – in fact I wrote a whole blog post about it a couple of years ago.  I don’t use it nearly as much anymore – I only have one client who has a VB.NET app.  I gotta say though, it’s weirdness like this that makes me not miss it much, cause that sure is a strange design decision.  It’s one of the very few times that a VB.NET feature is truly not on par with a similar C# one.

(See also: unexpected behavior when using VB.NET’s If() with nullable types:

Follow schneidenbach

Share article