Reputation: 2585
Ironically, while converting a bunch of old Arraylists to use generic List(Of foo) collections, to improve type safety, I encountered an unexpected behaviour in the List.AddRange()
method.
Given the following code, I would have expected a compiler error, but I don't get one, and the project runs until the AddRange call, where an 'Unable to cast List(Of bar) to List(Of foo)' exception is thrown.
Dim barList As List(Of bar) = BarFunctionsLib.GetBarList()
Dim fooList As New List(Of foo)
fooList.AddRange(barList)
Shouldn't my attempt to pass a List(Of bar) into an AddRange method on a List(Of foo) be picked up by the compiler? I've not been through my compiler settings in VS2015, perhaps they've been fiddled with in the past and now let this through?
Any ideas would be appreciated, as the whole justification of putting work into converting Arraylists to generic Lists was to prevent errors like this.
Upvotes: 2
Views: 77
Reputation: 32202
You need to turn on Option Strict
to get a compiler error about this - the simplest way is to put
Option Strict On
at the top of your source file.
A more robust solution for existing projects is to go to your project properties, and in the Compile section set it globally for your project.
As Tim mentioned in a comment however, the very best solution is to change your settings to default it on for all new VB projects:
Upvotes: 6