Friday, March 7, 2008

You insensitive bastard

Here's a really simple function that uses LINQ and will throw a bizarre exception when written in VB.NET. The exact same function, written in C# will work perfectly.

First, create a simple class


Public Class SearchCriteria
Public GroupName As String
Public Keyword As String
End Class


Then, add the following function to an NUnit test harness using VB.NET


Public Sub BadList()
Dim searchCriteria As New List(Of SearchCriteria)

Dim distinctSearchCriteria As New List(Of SearchCriteria)

distinctSearchCriteria = searchCriteria.Distinct()

End Sub



Running that code, results in the following exception


System.InvalidCastException : Unable to cast object of type 'd__80`1[SearchCriteria]' to type 'System.Collections.Generic.List`1[SearchCriteria]'.




Do you see why? Since it's been a long time since I've done VB.NET, it took me a while to figure this out. Of course my code wasn't that simple, but here's the solution:




Public Sub BadList()
Dim searchCriteriaList As New List(Of SearchCriteria)

Dim distinctSearchCriteria As New List(Of SearchCriteria)

distinctSearchCriteria = searchCriteriaList.Distinct()

End Sub




It goes back to VB.NET not being case sensitive. Declaring a variable with the same name as the class (albeit a different case), confused the hell out of the runtime engine.

This is just one of the many reasons I prefer C# to VB.NET. But the client wants the development done in VB.NET, so I get to (re)learn another language.

No comments: