Monday, April 25, 2011

C# doubt in GetType, Managed CodeGen

Consider the code,

Type t0 = Type.GetType("System.Drawing.dll");
Type t1 = Type.GetType("System.Drawing.Font");

Here in order to find type of "System.Drawing.Font" the assembly "System.Drawing.dll" is needed. how to use it.?

i.e wat if i do, so that value of t0 wont be null.??

Consider i ave a dll, proj.dll and i need to find the type of the class Class1 that is present in the dll.

From stackoverflow
  • Specify the assembly, including the version number for strongly named assemblies:

    Type t = Type.GetType("System.Drawing.Font,System.Drawing,"+
                          " Version=2.0.0.0, Culture=neutral, "+
                          "PublicKeyToken=b03f5f7f11d50a3a");
    

    Of course, if it's really just System.Drawing.Font (or another type you know at compile-time), use typeof:

    Type t = typeof(System.Drawing.Font);
    

    If you know another type in the same assembly at compile-time, you can use Assembly.GetType:

    Type sizeType = typeof(System.Drawing.Size);
    Assembly assembly = sizeType.Assembly;
    Type fontType = assembly.GetType("System.Drawing.Font");
    
    pragadheesh : Type t = Type.GetType("System.Drawing.Font,System.Drawing"); retruns values NULL to t..??? how to solve it.
    Andy : You need the specify the full name of the assembly, including version and public key. If you use the line that Jon posted in his answer, it should work.
    Jon Skeet : @Andy: The first version of my answer didn't have the version in. I suspected it was necessary, but didn't know it offhand. I posted a quick response indicating that, and then wrote the little test app.
    Ben Aston : the latter method is seriously useful, thanks
  • You want the System.Reflection.Assembly.Load method.

  • Pass the strong name of the assembly to load it, and then load the type from it, like

      Assembly asm = Assembly.Load("System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
                Type font = asm.GetType("System.Drawing.Font");
    
    pragadheesh : thanks. what if i want to add a class library dll and get the type of a class in the dll..? how to add that dll and find its Version,sulture and public key token.?

0 comments:

Post a Comment