alexroat
alexroat

Reputation: 1727

c# : Type.GetType called from a dll on exe type string

I've the following class in XmlSer.dll

namespace xmlser
{
        public class XmlSer
        {
                public Type test(string s)
                {
                    return Type.GetType(s);
                }

        //...other code

        }
}

and the following code in MyApp.exe, which links XmlSer.dll as a reference

namespace MyApp
{
    public class TestClass
    {
        public int f1 = 1;
        public float f2 = 2.34f;
        public double f3 = 3.14;
        public string f4 = "ciao";
    }

    class MainClass
    {

        public static void Main(string[] args)
        {
            TestClass tc = new TestClass();
            XmlSer ser = new XmlSer();
            Console.WriteLine(ser.test("MyApp.TestClass")!=null);
        }
}

Running MyApp.exe I get false, that means that ser instance of XmlSer is not able to get the type of Testclass (result is null). Putting XmlSer class directly in MyApp.exe code I correctly get the type of TestClass.

Checking on the net i've found that the problem is related to the assemblies. That means, the assembly of .exe is not visible to the XmlSer.test method so it can't resolve the type of TestClass.

How can I resolve the problem maintaing XmlSer in XmlSer.dll and MyApp.MainClass in MyApp.exe ?

Thanks.

Alessandro

Upvotes: 2

Views: 5618

Answers (3)

John Saunders
John Saunders

Reputation: 161773

Since the two are not in the same assembly, you probably need to include the assembly name in the type string:

Console.WriteLine(ser.test("MyApp.TestClass, MyApp")!=null);

If all you want to do is serialize arbitrary objects, you can do the following:

public static class Serialization
{
    public static void Serialize(object o, Stream output)
    {
        var serializer = new XmlSerializer(o.GetType());
        serializer.Serialize(output, o);
    }
}

Upvotes: 6

alexroat
alexroat

Reputation: 1727

I've found a definitive solution. I simply get the vector of all assemblies loaded from application. Then on each assembly I call Type.GetType till I get a valid Type. In this way you can obtain every type which is loaded in your process space regardless the assembly.

This below is the code of the function.

public static Type GetGlobalType(string s)
        {
            Type t=null;
            Assembly[] av = AppDomain.CurrentDomain.GetAssemblies();
            foreach (Assembly a in av)
            {
                t=Type.GetType(s + "," + a.GetName());
                if (t != null)
                    break;
            }
            return t;
        }

Cheers :)

Alessandro

Upvotes: 0

user76035
user76035

Reputation: 1536

Not sure, but maybe try ser.Test("MyApp.TestClass, MyApp")?

EDIT: Obviously MyApp not XmlSer

Upvotes: 3

Related Questions