title: Check if WMI ManagementObject query is Nothing instead of using a Try/Catch?
body: <p>In my program, I am using the the WMI interface to query lots of information about the hardware that the program is running on. I'm then taking that information and putting it into a list to help with displaying it later, but not much else is done beyond that at the moment. This method so far has worked out pretty well, but there is one major issue: sometimes the query is/returns (don't know which one yet!) <code>Nothing</code> and results in a <code>NullReferenceException</code>.</p>
  
  <p>Now, obviously I can wrap it in a Try/Catch and be on my merry way. However, I would like to avoid doing this because I will be querying hundreds of bits of information, and hundreds of them may result in an exception. This is just sloppy programming and is slowing my program down significantly!</p>
  
  <p>My questions is: What do I check in order to use an <code>If</code> instead of a <code>Try</code>? I will put my current code below and then list the solutions I have already tried.</p>
  
  <pre><code>    Public Shared Function GetSomeInfo() As List(Of String)
          Dim ret As New List(Of String)
          Dim sq As New Management.SelectQuery("Win32_Processor")
          Dim mos As New Management.ManagementObjectSearcher(sq)
          For Each info As Management.ManagementObject In mos.Get()
              ret.Add(TryQuery(info, "Name"))
              ret.Add(TryQuery(info, "Caption")) 'this query may result in Nothing somewhere...
          Next
          Return ret
      End Function
  
      Private Shared Function TryQuery(ByRef info As 
              Management.ManagementObject, ByVal strID As String) As String
          Try
              Return strID &amp; ": " &amp; info(strID).ToString 'exception obviously thrown here...but WHERE?
          Catch ex As NullReferenceException
              Return String.Empty
          Catch ex As Management.ManagementException
              Return String.Empty
          End Try
      End Function
  </code></pre>
  
  <p>So, here's what I've tried in order to attempt and get around using this <code>Try</code>:</p>
  
  <p><code>If Not info Is Nothing Then ...</code> Still resulted in some uncaught exception</p>
  
  <p><code>If Not info(strID) Is Nothing Then ...</code> Still got an exception somewhere</p>
  
  <p><code>If Not info.Equals(Nothing) Then ...</code> Desperation</p>
  
  <p><code>If Not Info(strID).ToString Is Nothing ...</code> :(</p>
  
  <p>I simply have no idea <em>where</em> to check for this exception being throwing within the WMI query. Any insight would be appreciated. Thanks!</p>