Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 726
Fiona - myaccessible.website Avatar asked Feb 08 '10 14:02

Fiona - myaccessible.website


People also ask

What are .NET generics?

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.

What is generics explain with an example?

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.

What is the purpose of using generics?

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.


2 Answers

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

like image 124
AakashM Avatar answered Nov 15 '22 06:11

AakashM


Have you got Option Strict turned on?

like image 44
stevehipwell Avatar answered Nov 15 '22 06:11

stevehipwell