Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 286
  • Last Modified:

.NET - how to find type by name?

Hi.

I need an ability to find type by name.
At the moment I'm using following code:

Type t = Type.GetType("System.Data.DataTable", false, true);

but it always returns null! :-(
Why?!

The application which is run this code has a reference to System.Data.dll, so I assume it must be able to find a "System.Data.DataTable".
Any ideas?
0
Dmitry_Bond
Asked:
Dmitry_Bond
  • 2
2 Solutions
 
markmiddlemistCommented:
The GetType method expects the assembly qualified name if the type (as here) isn't in Mscorlib.

Is this code to be used in such a way that different types are needed, or could you use typeof(System.Data.DataTable)

If not there is info here - http://msdn.microsoft.com/en-us/library/system.type.assemblyqualifiedname.aspx - on the AQN
0
 
Jacques Bourgeois (James Burger)Commented:
If you already have a DataTable, you can call GetType directly on your object. Otherwise, you can instantiate a new object in order to retrieve the type:

System.Data.DataTable tb = new System.Data.DataTable;
Type t = tb.GetType();

Otherwise, you need to know the name and path of the assembly (name of the dll) that contains the type to be able to retrieve the type information.
0
 
Dmitry_BondAuthor Commented:
The idea is to obtain a type by a string which is a name of type.
Is required for the C# scripting - just need a some special statement in script like "#using_type System.Data.DataTable", so by this directive application should automatically add a reference to "System.Data" assembly to parameters for a script code compiler...

Finally I have solved it by following code:

public static Type FindType(string pFullTypeName)
{
    Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
    foreach (Assembly asm in assemblies)
    {
        Type[] types = asm.GetTypes();
        foreach (Type t in types)
        {
            if (string.Compare(pFullTypeName, t.FullName, true) == 0)
                return t;
        }
    }
    return null;
}

Open in new window

0
 
Dmitry_BondAuthor Commented:
Nobody of commenters suggested a solution. Only markmiddlemist posted a useful link explaining why GetType does not work as I need it.
0

Featured Post

Free Backup Tool for VMware and Hyper-V

Restore full virtual machine or individual guest files from 19 common file systems directly from the backup file. Schedule VM backups with PowerShell scripts. Set desired time, lean back and let the script to notify you via email upon completion.  

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now