views:

115

answers:

3
+6  Q: 

Generics in VB.NET

Now, as a C# programmer, I know that generics are awesome. However, when dabbling in some VB.NET, I discovered that the following does not cause a compiler error:

Dim instance As List(Of Integer)
instance.Add(True)

Why is this? I know that you are not required to cast in VB.NET, but I'd have thought that this kills the main reason to use generics - type safety.

Edit: I do not have option strict on, as this wasn't a real programming exercise, just me having a look at VB.NET in theory. It is a theoretical question, as I was expecting it to cause a compiler error even with option strict off, just as a feature of generic types.

+3  A: 

Have you got Option Strict turned on?

Stevo3000
+10  A: 

Without Option Strict On, VB.NET is happy to implicitly convert Boolean to Integer. I strongly recommend (especially coming from a C# background) that you make Option Strict On the default for your VB.NET work.

You can do this in Visual Studio in Tools | Options | Projects and Solutions | VB Defaults.

edit for more on the VB (classic) 'relaxed' attitude to type conversion, google 'Evil Type Coercion'. Those of us who sought to do good work in VB (classic) had to wrestle this demon for while...

AakashM
+1 Here's the original and best criticism of evil type coercion in VB, written in 1995 when it was introduced, and still relevant today. http://vb.mvps.org/articles/pt199511.pdf
MarkJ
A: 

VB.NET converts at the function call site. The List(of Integer) is still storing an integer (-1, which is the integer value of True)

Jimmy
Whoever came with the idea to represent a _positive_ truth value with a _negative_ numerical value should have his head examined.
Rik
@Rik... -1 is all bits high. False is 0 because all bits are off.
Matthew Whited
@Matthew Whited: Admittedly, that makes some sense. Still, I like the 0/1 convention a lot better.
Rik
@Rik: there is nothing stopping use from using 1 as true. Any integer other then 0 will be converted to true. The standard is -1 because of signed integers and all bits high being the direct opposite of all bits low. It was odd the first few times I saw it as well. But after working with electronics and digital electronics... it made much more sense.
Matthew Whited