tags:

views:

166

answers:

1

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()
+1  A: 

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
But jon skeet i am using only a simple console app created in vs 2008..in the main() i typed this and got different results for C# and vb. I am not using my own custom assembly. Just create two console app in C# and vb.net in same solution and use the code i typed earlier. Thanks.
Yes, one of the assemblies that's being reflected into *is* that console app though.
Jon Skeet
Excellent explanation. Thanks Guru!