Search code examples
c#vb.netcoding-stylecase-sensitivecase-insensitive

Are there issues using Dim foo As Foo in VB.NET?


In a recent VB.NET project I adopted the naming conventions I'm used to using in C#. Namely, often calling a variable the same name as the class it references, only with a different case, e.g.

Foo foo = new Foo(); // C#

Dim foo As New Foo() ' VB.NET

I find this is often the clearest way to write code, especially for small methods. This coding style obviously works fine in C#, being case sensitive, and because of the syntax highlighting provided by Visual Studio, it is very easy to see that the class name and the variable name are different.

However, to my surprise, this also worked fine nearly 100% of the time* in VB.NET. The only issue was that the variable name then appeared to take on a multiple identity. Namely it could be used to call both instance methods and Shared (static) methods of the Foo class. This didn't really cause any problems though, it just meant that Intellisense would provide a list containing both static and instance methods after you hit the '.' after the variable name.

I found, again to my surprise, that this didn't actually lead to any confusion in my project, and it's been very successful so far! However I was the only person working on this particular project.

Here is a slightly longer example:

Dim collection as Collection = New Collection()
For Each bar As Bar in Bar.All()
    collection.SomeInstanceMethod(bar)
Next
collection.SomeSharedMethod()

* The only issue I found with this was that sometimes the 'Rename' refactoring tool got confused, i.e. when renaming a class it would rename the variables with the same name as the class as well, in their declaration lines (Dim foo As...), but not the other references to that variable, causing compiler issues (duh). These were always easy to correct though.

Another small annoyance is that the VB.NET syntax highlighter doesn't highlight class names any differently than variable names, making it not quite as nice as when using it in C#. I still found the code very readable though.

Has anyone else tried allowing this in a team environment? Are there any other potential issues with this naming convention in VB.NET?


Solution

  • I'm going to differ with the rest of the answers here... I don't think there is any problem with doing this. I do it regularly, and have absolutely 0 problems resulting from it.

    If you use lowercase for the variable name you can easily differentiate the variable from the type, and the compiler will not confuse the two identifiers.

    If you delete the variable declaration, the compiler will think other references to this variable now refer to the type, but it's not really a problem because those will be tagged as errors.