Yisroel M. Olewski
Yisroel M. Olewski

Reputation: 1628

How to make AddRange type-safe

I have this dummy code in vb.net

Sub dummy()
    Dim a = New List(Of XDocument)
    Dim b = New List(Of Net.Mail.MailAddress)
    b.AddRange(a)
End Sub

Obviously, this cant ever work. but the compiler ignores it.

How can I force VS to flag this at compile time?

Thanks

Upvotes: 0

Views: 26

Answers (1)

jmcilhinney
jmcilhinney

Reputation: 54427

The compiler only allows that because you have Option Strict Off. You should basically ALWAYS have Option Strict On at the project level and only set it Off at the file level on the very rare occasions that you actually need to use late-binding. Even then, you should only set it Off in those specific files that actually require it and you should use partial classes to keep the code in those files to an absolute minimum.

Set Option Strict On in your project properties and the compiler will correctly flag that as bad code and there's every chance that you'll see other problem areas highlighted too. You should also set it On in the VS options, so that it will be On by default for all future projects.

Upvotes: 3

Related Questions