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.
NET: A generic type definition is a class, structure, or interface declaration that functions as a template, with placeholders for the types that it can contain or use.
Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types.
In a nutshell, generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods. Much like the more familiar formal parameters used in method declarations, type parameters provide a way for you to re-use the same code with different inputs.
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...
Have you got Option Strict turned on?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With