Type.GetType("ObjectName");

  • Thread starter Thread starter Jon
  • Start date Start date
J

Jon

Hello all,

I'm trying to do the above, pass in an object name and it return the
type, but it's erroring, I've seen something like this before but
can't quite remember. Can this be done?

Thanks

Jon
 
The following is lifted verbatim from the MSDN Documentation. Hopefully it
will help clear things up:

using System;
namespace MyTypeNameSpace
{
class MyClass
{
public static void Main(string[] arg)
{
try
{
// Get the type of a specified class.
Type myType1 = Type.GetType("System.Int32");
Console.WriteLine("The full name is {0}.", myType1.FullName);
// Since NoneSuch does not exist in this assembly, GetType
throws a TypeLoadException.
Type myType2 = Type.GetType("NoneSuch", true);
Console.WriteLine("The full name is {0}.", myType2.FullName);
}
catch(TypeLoadException e)
{
Console.WriteLine(e.Message);
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}

-- Peter
Site: http://www.eggheadcafe.com
UnBlog: http://petesbloggerama.blogspot.com
Short urls & more: http://ittyurl.net
 
I'm trying to do the above, pass in an object name and it return the
type, but it's erroring, I've seen something like this before but
can't quite remember. Can this be done?

What's the error?
Unable to find the type? Check that it's the correct assembly from where you
are loading...


--
Happy Hacking,
Gaurav Vaish | www.mastergaurav.com
www.edujini-labs.com
http://eduzine.edujini-labs.com
-----------------------------------------
 
Hello all,

I'm trying to do the above, pass in an object name and it return the
type, but it's erroring, I've seen something like this before but
can't quite remember. Can this be done?

Thanks

Jon

hi , what is your environment ? are you doing it in asp.net and your
cusotm objects if yes, the problem is that this object lives in
another assembly whose name you do not know, if this is the this is a
workaround, it works only if all classes are in same directory
(app_code) which will be compiled to same dll

//
Type rootType = typeof (SomeClassFromAppCode);
string fullAssemblyName = rootType.Assembly.FullName;

string fullClassName = typeName +", " + fullAssemblyName;
Type type = Type.GetType(fullClassName);
 
Type rootType = typeof (SomeClassFromAppCode);
string fullAssemblyName = rootType.Assembly.FullName;

string fullClassName = typeName +", " + fullAssemblyName;
Type type = Type.GetType(fullClassName);


Better use:

rootType.Assembly.GetType(typeName)

The code written above will be slower because of unnecessary overheads.


--
Happy Hacking,
Gaurav Vaish | www.mastergaurav.com
www.edujini-labs.com
http://eduzine.edujini-labs.com
-----------------------------------------
 
Back
Top