views:

20

answers:

2

In visual studio 2008, when I use something akin to the following snippet:

Dim myVar
.... ' all sorts of stuff that might initialise myVar '
if not isNothing(myVar) then
   myVar = new Object()
end if
myVar.ToString()

visual studio warns me on the last statement that myVar might be uninitialised, and a nullreference exception could occur.

To me it seems desirable to suppress that message in this situation.

  1. Am I right in wanting to suppress that warning here, or am I overlooking something?
  2. Is it possible to suppress a warning here.

Note that I don't want to suppress the warning in general, only if I'm sure it makes no sense here.

+1  A: 

Am I right in wanting to suppress that warning here, or am I overlooking something?

No you are not right. If there's a condition under witch the variable might not get initialized you will get into trouble. So it would be better to always initialize variables:

Dim myVar as SomType = Nothing
Darin Dimitrov
+1  A: 

I think that if you change the line:

Dim myVar 

To:

Dim myVar = Nothing

The warning will go away.

Another issue though is that you really shouldn't declare stuff as Dim myVar, it should be Dim myVar As Object in that case. You should always set Option Explicit On in VB.Net. It'll save you from a lot of potential hard to find bugs in the future.

ho1