Nothing vs Null

VB.Net’s Nothing keyword is is not the same as C#’s null.  MSDN states, “Assigning Nothing to a variable sets it to the default value for its declared type. If that type contains variable members, they are all set to their default value”.

In other words, the Nothing keyword is actually equivalent to C#’s default(T) keyword, where T is the type that the expression is used as.

This can lead to nasty surprises with nullable types in conditional operators. 
In C#, the expression (...) ? null : 1 will not compile, since “there is no implicit conversion between '<null>' and 'int'”.    Since  null is an untyped expression, the type of the conditional is inferred to be int, resulting in an error because null cannot be converted to int.

In VB.Net, by contrast, the equivalent expression, If((...), Nothing, 1), will compile, but will have unexpected results.  Here too, Nothing is an untyped expression, so the type of the conditional is inferred to be Integer.  However, unlike null, Nothing can be converted to Integer, so this is compiled as If((...), 0, 1),  which is probably not what the programmer intended.

In both languages, the solution is to use an expression which is actually typed as int?, by writing new int?(), (in C#) or New Integer?() (in VB.Net).


This publication is excellent. Clarie

I liked the complete article…. top notch written,thank you for all of the information you have got furnished. so that it will depart meaningful blog remarks one need to read, apprehend and examine the weblog submit.
Zagraj teraz
gry friv for free!

It's clear for me that information from will be useful for teachers. It will help you to write resume

Post a Comment