Logo
PRB: FullName and Name properties of EnvDTE.CodeElement return exceptions for using/Imports statements of C# and VB.NET

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

This article discusses the behavior of the FullName and Name properties of EnvDTE.CodeElement for 'using' statements of C# and 'Imports' statements of VB.NET.

More Information

While the automation model (EnvDTE) of Visual Studio .NET 2002/2003 did not consider the 'using' statements of C# and 'Imports' statements of VB.NET (used to import namespaces) as code elements, the automation model of Visual Studio 2005 and higher does so, mapping them to  EnvDTE.CodeElement. However, the Name and FullName properties of EnvDTE.CodeElement can cause the following problems:

C#:

  • The FullName property causes COMException (0x80004005).
  • The Name property causes COMException (0x80004005).

VB.NET:

  • The FullName property causes NotImplementedException.
  • The Name property works correctly.

The workaround is to cast the EnvDTE.CodeElement class to the new EnvDTE80.CodeImport class introduced by the automation model (EnvDTE80) of Visual Studio 2005 and use the CodeImport.Namespace property.

The following macro provides the code to reproduce the problem and the workaround. It gets the first code element of the active code window and it shows its Name and FullName properties:

Language: VB.NET   Copy Code Copy Code (IE only)
Sub Macro1()

   Dim codeElement As EnvDTE.CodeElement
   Dim codeImport As EnvDTE80.CodeImport

   codeElement = DTE.ActiveDocument.ProjectItem.FileCodeModel.CodeElements.Item(1)

   Try
      ' This fails in C#, it works in VB.NET
      MsgBox("EnvDTE.CodeElement.Name: " & codeElement.Name)
   Catch ex As Exception
      MsgBox(ex.ToString())
   End Try

   Try
      ' This fails in both C# and VB.NET
      MsgBox("EnvDTE.CodeElement.FullName: " & codeElement.FullName)
   Catch ex As Exception
      MsgBox(ex.ToString())
   End Try

   codeImport = DirectCast(codeElement, EnvDTE80.CodeImport)

   Try
      ' This works in both C# and VB.NET
      MsgBox("EnvDTE80.CodeImport.Namespace: " & codeImport.Namespace)
   Catch ex As Exception
      MsgBox(ex.ToString())
   End Try

End Sub

Go back to the 'Resources for Visual Studio .NET extensibility' section for more articles like this


Top