Question

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?

Was it helpful?

Solution

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?

OTHER TIPS

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)

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.

I don't know the history, but yes it was a VS 2008 enhancement.

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