1

For testing purposes,

I'm trying to construct a scenario in which I have two different dlls with the same namespace, class and method name.

E.g.

DLL1:

namespace SomeNamespace
{
    public class Foo
    {
        public static string Bar()
        {
            return "A";
        }
    }
}

DLL2:

namespace SomeNamespace
{
    public class Foo
    {
        public static string Bar()
        {
            return "B";
        }
    }
}

I'm trying to write code which dynamically calls Foo.Bar() in order to get exception of ambiguity.

In the code I have I specifically need to pass the dll name as a parameter, which I want to avoid.

        Assembly a = Assembly.LoadFile(dllPath);

        Type t = a.GetType(typeName);

        MethodInfo method = t.GetMethod(methodName);

        var result = new object();

        if (method.IsStatic)
        {
            result = method.Invoke(null, null);
        }

        else
        {
            object instance = Activator.CreateInstance(t);

            result = method.Invoke(instance, null);
        }

Is there a way to casue this exception?

Y.S
  • 1,860
  • 3
  • 17
  • 30

1 Answers1

0

If both assemblies have the same assembly name you can use Type.GetType(string) like this: https://stackoverflow.com/a/6465096/613130, so

Type t = Type.GetType("SomeNamespace.Foo,SomeAssembly");

I don't think there is a .NET method to search for a Type in all the loaded assemblies.

Community
  • 1
  • 1
xanatos
  • 109,618
  • 12
  • 197
  • 280
  • Please Correct me if i'm wrong here, but doesn't the "SomeAssembly" part after the comma will go and search for SomeAssembly.dll in the binary folder? I can't have two dlls of the same name there – Y.S Aug 13 '15 at 08:42
  • @Y.S The `AssemblyName` is set during compilation (right click on the project, Properties, Application, Assembly Name)... Clearly you'll need a `SomeAssembly.dll` and `SomeAssembly2.dll`, both with `SomeAssembly` as assembly name (so you'll need to manually rename one of them). Then you load both of them with `Assembly.LoadFile` . Totally untested. – xanatos Aug 13 '15 at 08:46
  • Funny thing, when I try to load it using GetType, im getting null as the response, was expecting an exception. If I remove one of the assemblies reference I'm getting the type back, so the null is clearly returned beacuse of the second assembly. – Y.S Aug 13 '15 at 09:45
  • @Y.S I had that doubt... Looking at the `Type.GetType(string)` there is no mention of an exception if there is an ambiguous resolution... So perhaps it isn't possible at runtime to generate one. – xanatos Aug 13 '15 at 09:47