PRB: Solution.AddXXX and ProjectItems.AddXXX methods return Nothing (null)

Author: Carlos J. Quintero (Microsoft MVP) Applies to: Microsoft Visual Studio 2005
Date: February 2006   Microsoft Visual Studio 2008
Updated: March 2013   Microsoft Visual Studio 2010
      Microsoft Visual Studio 2012

This article explains why the several Solution.AddXXX and ProjectItems.AddXXX methods (AddFromTemplate, etc.) return Nothing (null).

More Information

The following macro reproduces the problem:

Sub AddFromTemplate()

   Dim objSolution2 As EnvDTE80.Solution2
   Dim sTemplateFullFileName As String
   Dim colProjectItems As ProjectItems
   Dim objProjectItem As ProjectItem
   Dim sTargetFileName As String

   objSolution2 = CType(DTE.Solution, EnvDTE80.Solution2)

   sTemplateFullFileName = objSolution2.GetProjectItemTemplate("Class.zip", "VisualBasic")
   sTargetFileName = "Test.vb"
   colProjectItems = objSolution2.Projects.Item(1).ProjectItems
   objProjectItem = colProjectItems.AddFromTemplate(sTemplateFullFileName, sTargetFileName)

   If objProjectItem Is Nothing Then
      MessageBox.Show("ProjectItem is Nothing")
      MessageBox.Show("ProjectItem: " & objProjectItem.Name)
   End If

End Sub

When you run the macro the new file is added to the project but the ProjectItem is returned Nothing. This happens because using a template the wizard could add zero, one or several files and the only case when it would make sense to return a ProjectItem would be when only one file is added, but Microsoft considered that it would be confusing to return sometimes Nothing and sometimes a ProjectItem, so Nothing is always returned. Also, wizards can't return to the caller the file which was added, and since the target filename is not always honored, the methods return Nothing to play safe.

As a workaround, if the target filename was honored by the wizard, you can retrieve the ProjectItem using:

objProjectItem = colProjectItems.Item(sTargetFileName)

Go to the 'Visual Studio Extensibility (VSX)' web site for more articles like this (Articles section)