Question

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.

Was it helpful?

Solution

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...

OTHER TIPS

Have you got Option Strict turned on?

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)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top