Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

History of VB.NET Nullable syntax

I can't find a definitive answer. Since C# 2.0 you've been able to declare

int? i = 125;

as shorthand for

Nullable<int> i = Nullable<int>(123);

I recall reading somewhere that VB.NET did not allow this shortcut. But low and behold, I tried it in VS 2008 today and it works.

Does anyone know whether it's been this way since .NET 2.0 or was this added later?

like image 506
Larsenal Avatar asked Oct 21 '08 22:10

Larsenal


3 Answers

System.Nullable was introduced in .Net 2.0 and is available to VB as a generic type. You just cannot use the nullable syntax. So in VS 2005 you can do:

Dim x as Nullable(of Integer)

I don't know if null equivalence and boxing works for nullables in VB 2005, but I would suspect that the answer is yes since the .Net team made a change to the 2.0 CLR to accomplish boxing with nullables. I would imagine VB leverages this.

In 2008, you can obviously just do:

Dim x as Integer?
like image 184
Jason Jackson Avatar answered Oct 15 '22 19:10

Jason Jackson


it works in VB 2005 (dotnet 2.0) but it's ugly.

You can't use it like a normal variable, I thought it might work like an Object type but it doesn't.

Rather than this:

dim oInt as object

dim i as integer

if oInt is nothing then 

    msgbox("int is null")
else

    i = cint(oInt)

end if

you have this.

Dim oInt as nullable(of integer)

dim i as integer

if oInt.HasValue = false then 

    msgbox("int is null")

else

   i = oInt.Value

end if

The problem here is that if your variable is null and you happen to invoke the Value property it barfs up an unhandled exception.

so for instance, my favorite one is this.

AddParamToSQLCmd(sqlCmd, "@SomeID", SqlDbType.Int, 0, ParameterDirection.Input, iif(oInt.HasValue, oInt.Value, DBNull.value))

Will result in an runtime error when your Supposed Nullable value is null!!!

so here's nullable(of integer) vs Object code

nullable(of integer)

if oInt.HasValue then 
    AddParamToSQLCmd(sqlCmd, "@SomeID", SqlDbType.Int, 0, ParameterDirection.Input, oInt.Value)
else
    AddParamToSQLCmd(sqlCmd, "@SomeID", SqlDbType.Int, 0, ParameterDirection.Input, dbnull.value)
end if

Object

AddParamToSQLCmd(sqlCmd, "@SomeID", SqlDbType.Int, 0, ParameterDirection.Input, oInt)
like image 22
user23462 Avatar answered Oct 15 '22 18:10

user23462


IIRC, nullable types were introduced in .NET 2.0 at a very late stage. The C# compiler team managed to cram in more language support for them than the VB.NET team did. The VB.NET team more or less caught up in VS2008. That's why you can, for example, use the == operator to compare nullables in C# 2.0 whereas in VB.NET you had to put up with the Nullable.Equals() method. Grrr.

like image 30
Christian Hayter Avatar answered Oct 15 '22 19:10

Christian Hayter