views:

136

answers:

2

I have an asp.net web project that references a domain project.

From within the web project, I want to create an instance of a class from the domain project using reflection, but I always get null (Nothing, in VB).

NOTE: I am using the non-fully qualified class name, and was hoping that a search would be performed as MSDN seems to indicate (at the Assembly level)

Dim myType as Type = Type.GetType("MetricEntity") '// yields Nothing (Null)

  '// lets try this
  Dim WasFound As Boolean = False
  For Each ObjectType In Me.GetType.Assembly.GetExportedTypes
    If ObjectType.Name = theClassName Then
      WasFound = True
      Exit For
    End If
  Next

The answer to this question seems to typically be:

Dim myType as Type = Type.GetType("System.Linq.Enumerable, System.Core, " 
     + "Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")); 

But I don't see the logic of having to hardcode the version number (or have to place in a config file)....so what happens if the version changes and I forget to update it in the reflection code.....is it possible to do a GetType, ignoring Version, Culture, and PublicKeyToken?

+1  A: 

You can do something like this, ignoring those attributes:

Dim myType as Type = Type.GetType("System.Linq.Enumerable")); 

or:

Dim myType as Type = Type.GetType("System.Linq.Enumerable, System.Core")); 
Nick Craver
Thanks. Note to others....the second syntax is necessary for a class that resides in an external assembly, ie: if you do the Type.GetType from your web project on a class from your domain project, you MUST specify the assembly.
tbone
+2  A: 

You can get a type by name alone if you have the Assembly it's in. Would that work for you?

That way you could specify the assembly name in a separate location from the types you're trying to access.

Assembly assembly = typeof(System.Linq.Enumerable).Assembly;
Type type = assembly.GetType("System.Linq.Enumerable");
280Z28
+1 Works well - thanks!
Dan