Thursday, March 31, 2011

assembly.GetExportedTypes() show different result

Why does assembly.GetExportedTypes() show different result in C# and VB.NET?

These two give different results

var v = from a in AppDomain.CurrentDomain.GetAssemblies() from b in a.GetExportedTypes() select b; 
v.Count(); 

Dim v = From a In AppDomain.CurrentDomain.GetAssemblies(), b In a.GetExportedTypes()     Select b v.Count()
From stackoverflow
  • When you compile a VB.NET assembly, it includes some extra "helper" types. Use Reflector to have a look at your compiled assembly to see what I mean.

    I'm pretty sure you'll find that the only assembly with any differences in is the one you're using to do the reflection - i.e. the one which is built with either C# or VB.NET, depending on your scenario.

    EDIT: It depends on exactly how you define your classes.

    However, again this is only relevant to the code being compiled by the C# or VB compiler. When you call GetExportedTypes it doesn't matter what language you're calling from. You're getting confused by the fact that you're only writing out the total count. Here are two short but complete programs to show the difference:

    C#

    using System;
    using System.Reflection;
    
    public class ShowTypeCounts
    {
        static void Main()
        {
            AppDomain domain = AppDomain.CurrentDomain;
            foreach (Assembly assembly in domain.GetAssemblies())
            {
                Console.WriteLine("{0}: {1}",
                                  assembly.GetName().Name,
                                  assembly.GetExportedTypes().Length);
            }
        }
    }
    

    Results:

    mscorlib: 1282
    ShowTypeCounts: 1
    

    VB

    Imports System
    Imports System.Reflection
    
    Public Module ShowCounts
    
        Sub Main()
            Dim domain As AppDomain = AppDomain.CurrentDomain
    
            For Each assembly As Assembly in domain.GetAssemblies
    
                Console.WriteLine("{0}: {1}", _
                                  assembly.GetName.Name, _
                                  assembly.GetExportedTypes.Length)
    
            Next
        End Sub
    
    End Module
    

    Results:

    mscorlib: 1282
    ShowTypeCounts: 1
    

    As you can see, the results are the same - but if you remove "public" from either piece of code, the ShowTypeCounts result goes down to 0. This isn't a difference of how GetExportedTypes works between languages - it just depends on what types you're actually exporting.

    My guess is that in your console apps, one had a public type and the other didn't.

    Jon Skeet : Yes, one of the assemblies that's being reflected into *is* that console app though.

0 comments:

Post a Comment